ibvasi
11/26/2016 - 12:22 AM

Coercion

Coercion

/* 
  An explicit conversion occurs when you use the CONVERT or CAST keywords explicitly in your query
  An implicit conversion arises when you have differing datatypes in an expression and SQL Server casts them automatically according to the rules of datatype precedence
  For example nvarchar has higher precedence than varchar
*/

// For numbers Coercion works if the value is non-zero
var a = 10;
if (a) {
    console.log("a is true");
} else {
    console.log("a is false");
}
// a is true

var b = -10;
if (b) {
    console.log("b is true");
} else {
    console.log("b is false");
}
// b is true

var c = 0;
if (c) {
    console.log("c is true");
} else {
    console.log("c is false");
}
// c is false because the value of c is 0

// For string Coercion works as long as it is not an empty string
var d = "hello";
if (d) {
    console.log("d is true");
} else {
    console.log("d is false");
}
// d is true

var e = " ";
if (e) {
    console.log("e is true");
} else {
    console.log("e is false");
}
// e is false because it is an empty string

// For boolean
var f = true;
if (f) {
    console.log("f is true");
} else {
    console.log("f is false");
}
// f is true 

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

// For null
var h = null;
if (h) {
    console.log("h is true");
} else {
    console.log("h is false");
}
// h is false

// For undefined
var i = undefined;
if (i) {
    console.log("i is true");
} else {
    console.log("i is false");
}
// i is false

/* 
  Summary
  JavaScript is flexible with typing  
  Values of all types have an associated Boolean value
  Use === for precise checks (both value and type)
  For numbers coercion works as long as the number is non-zero
  For strings it works as long as the string is not an empty string
  For null and undefined it is false
  For boolean is is true if the value is true and false if the value is false
*/