Showing posts with label undefined. Show all posts
Showing posts with label undefined. Show all posts

Saturday, 22 December 2018

What is the value of unassigned properties of an object?

If you do not assign any value to a property, then the value is undefined.

HelloWorld.js
class Employee{
  constructor(firstName, lastName){
    this.firstName = firstName;
    this.lastName = lastName;
  }
}

var emp = new Employee();

console.log(emp.firstName + " : " + emp.lastName);

Output
undefined : undefined

Previous                                                 Next                                                 Home

Is undefined a JavaScript keyword?

undefined is not a JavaScript keyword, it is a property of global object, i.e., it is a variable in global scope.

You can shadow the global property undefined in local scope.

HelloWorld.js
function print_me () {
    console.log(undefined)
    var undefined = "shadowed";
    console.log(undefined);
}

print_me();

Output
undefined
shadowed


Previous                                                 Next                                                 Home

Sunday, 9 December 2018

JavaScript: How the extra commas are interpreted in Array Literal notation

Given below array, which has two commas with no data, how it is interpreted.
var arr = ["Cricket", , "Football"]

Missing elements in the array are treated as undefined.

HelloWorld.js
var arr = ["Cricket", , "Football"]

console.log("arr[0] : " + arr[0]);
console.log("arr[1] : " + arr[1]);
console.log("arr[2] : " + arr[2]);

Output
arr[0] : Cricket
arr[1] : undefined
arr[2] : Football


Previous                                                 Next                                                 Home

Saturday, 8 December 2018

How the undefined variable behaves in boolean and numeric context?

'undefined' variable is treated as false in boolean context.

HelloWorld.js
var x;

if(x){
  console.log("x is true");
}else{
  console.log("x is false");
}

var y = true;
if(y){
  console.log("y is true");
}else{
  console.log("y is false");
}

Output
x is false
y is true

undefined leads to NaN in numeric context.

HelloWorld.js
var x;

var y = x + 10;

console.log("Value of y is : " + y);

Output
Value of y is : NaN



Previous                                                 Next                                                 Home

Friday, 7 December 2018

How to check a variable has a value or not?

By using ‘undefined’, you can check whether a variable has a value or not.

HelloWorld.js
function do_something() {
  var x = 100;
  
  if(x === undefined){
    console.log("x is undefined");
  }else{
    console.log("Value of x is : " + x);
  }
  
  var y;
  
  if(y === undefined){
    console.log("y is undefined");
  }else{
    console.log("Value of y is : " + y);
  }
}

do_something();

Output
Value of x is : 100
y is undefined



Previous                                                 Next                                                 Home