JS Learnings – 1


JavaScript is dynamically typed.

This unassumingly simple feature is one of the most powerful strengths of the language. As your experience with the language evolves you will appreciate the less ceremony involved in creating variables


// JAVASCRIPT IS DYNAMICALLY TYPED
var age = 30;
console.log("Age = " + age); // Display's age
console.log("Type of variable age = " + typeof(age)); // Type of variable
console.log("— Dynamically typed —")
age = "new born"; // Proof JavaScript is dynamically typed
console.log("Type of variable age = " + typeof(age)); // Type has changed

 

JavaScript has types that are not common in other languages. Type such as “undefined” when operated with number produces NaN (Not a number type), which could be confusing for beginners. To add to the confusion type of NaN is a number thus any arithmetic operation to NaN is never going to throw an exception. More info on variables can be found here.

JavaScript types in action.

 


// Variables declared by default are undefined
console.log("Begin example – 2");
var x,y = 10;
console.log("Value of x = " + x); // X value is not defined, hence has undefiend
console.log("Value of y = " + y);
// Types demystified
console.log("Type of x = " + typeof(x)); // Type of undefined is undefined.
console.log("–");
var a=null;
var b=0;
console.log("Value of a = " + a); // a value is null
console.log("Value of b = " + b);
console.log("Type of a = " + typeof(a)); // Type of null is object.
console.log("–");
var c = a/b;
console.log("Value of c = " + c);
console.log("Type of c = " + typeof(c)); // Type of NaN is number.
console.log("–");

view raw

types.js

hosted with ❤ by GitHub

 

Truthy/Falsy explained

 


console.log("Begin example – 3");
var p = 0; // Try replacing this with null, undefined, NaN
console.log("Value of p = " + p);
console.log("Boolean equivalent of p = " + Boolean(p)); // Truthy or Falsy value
// Example usage of truthy or falsy
if (p){
console.log("I am happy");
} else {
console.log("I am not sure");
}

view raw

truthy.js

hosted with ❤ by GitHub

Leave a comment

Your email address will not be published. Required fields are marked *