if(1 == "1")
The same as
if(1 == 1)
if("1" == "1")
Strings and String Conversion
var someNumber = 2; var someString = 'abc'; var newString = someString + someNumber; console.log(newString); // 'abc2'
In fact, anytime we “add” anything to a string, it turns it into a string
var someTruth = true; var someString = 'abc'; var newString = someString + someTruth; console.log(newString); // 'abctrue';
And it doesn’t matter where we put the string.
var someTruth = true; var someString = 'abc'; var newString = someTruth + someString; console.log(newString); // 'trueabc';
Numbers and Number Conversion
But what happens if the string contains a number and we add that to a number? Well, it depends.
var someNumber = 9; var someString = '3'; var newString = someString + someNumber; console.log(newString); // '39';
var someNumber = 9; var someString = '3'; var newString = someNumber + someString; console.log(newString); // '93';
var someNumber = 9; var someString = '3'; var newString = someNumber + +someString; console.log(newString); // 12;
Well, prefixing the string variable with + converts that string to a number. Under the hood, it is the same as if we had used the Number function to convert the string to a number.
var someNumber = 9; var someString = '3'; var newString = someNumber + Number(someString); console.log(newString); // 12;
But what if someString can’t be converted to a number?
var someNumber = 9; var someString = 'x'; var newString = someNumber + Number(someString); console.log(newString); // NaN;
var someNumber = 9; var someString = 'x'; var newString = someNumber + +someString; console.log(newString); // NaN;
Boolean and Boolean Conversion
You can convert any type to a Boolean value simply by putting a bang in front of it
It doesn’t just invert the truthiness or falsiness of anyVariable, it actually converts it to a Boolean first and then inverts the Boolean value.
In some code, you may see
- WebForms vs MVC–The War Is Over - September 25th, 2014
- Create A Desktop Application using Angular, Bootstrap and C# - October 15th, 2015
- Are You Doing Angular Right? - November 5th, 2015
- Adventures Working With Angular’s $scope - November 26th, 2015
- Using Gulp to Bundle, Minify, and Cache-bust - January 28th, 2016
- Reactions to React JS and Associated Bits - March 17th, 2016
- An Explanation of the Flux Pattern - March 31st, 2016
- Ext JS 6 by Sencha - The Good, The Bad, The Ugly - April 7th, 2016
- Do This To Increase Your Client Side Web Development Speed - April 21st, 2016
- ES2015 Code Coverage and Jest (React JS Unit Testing) - May 5th, 2016
- 4 Reasons To Drop MVVM - July 27th, 2016
- You Can Start Using Node Today - August 2nd, 2016
- TypeScript and Electron The Right Way - September 6th, 2016