Modern mode Js — use strict And Power of Nullish coalescing operator (??) and Optional chaining(?.)
In This article we will discuss about the strict mode and new js features Nullish coalescing operator and optional chaining.Using of these features we can write our code more clean and precise way .
Let’s start with Strict mode . Many of you have seen written code like below in many files at the top.
'use strict'
What’s it ? Why we use it ? It’s mandatory to use? 🤔 Hold on!!!
I’ll briefly clear your each doubts !!! And then it’ll be easy-peasy for all of you!!
If you follow JS from starting or you have read somewhere that for a long time, JavaScript evolved without compatibility issues. New features were added to the language while old functionality didn’t change.
That had the benefit of never breaking existing code. But the downside was that any mistake or an imperfect decision made by JavaScript’s creators got stuck in the language forever..
Let’s understand mistake or an imperfect decision made by JavaScript’s creators with an example which will give you better clarity.
example.js
function sum(a,b){
res = a+b;
console.log(res);
}
sum(10,20);
If you will run this code you may expect an error i.e. (Uncaught ReferenceError: a is not defined)
, if you have some basic knowledge of other language like c,java etc. then you know that you can’t access a variable before declare that.
But in this case you will get the output in browser console: 30
.
In the above example if we have declared res
like let res;
then it will right.
I know many of you surprised with wrong output.But this is not only single unexpected/wrong behaviour of JS there are few many.😨
You can google for more such mistakes!!!!
Till ES5 was not introduced we didn’t had any solution for that.But ES5 comes with a features called 'use strict'
that enables the strict mode for JS code.
Note: Since Js added or evolve the new features with support of old functionality.So by default strict mode is
disabled.
What is ‘use strict’ ?
This is a Js feature which was introduced in ES5 , to enable the strict mode in scripting file to tackle the unexpected or wrong behaviour of old functionality and give the standard result.
To enable the strict mode we have to added the directive looks like a string: "use strict"
or 'use strict'
.
To work strict mode we have to placed 'use strict'
at the top ,otherwise it will not enabled from starting of the file or may not be enabled.
Let’s understand with an example:
example1.js
"use strict";
function sum(a,b){
res = a+b;
console.log(res);
}sum(10,20);
example2.js
function sum(a,b){
res = a+b;
console.log(res);
}
"use strict";
sum(10,20);
In the above, example1.js will give error that Uncaught ReferenceError: res is not defined
and example2.js gives output 30 .Because strict mode is enable in whole file of example1.js because we placed ‘use strict’
at the top while in example2.js strict mode enable after sum definition and that code is ignored.So always placed ‘use strict’
at the top.
Note: There is no directive like
"no use strict"
that reverts the engine to old behaviour. Once we enter strict mode, there’s no way to cancel.
There are a list of many more scenarios in JS where you will get the unexpected and wrong result if you don’t enable strict mode.
Should we always add ''use strict'' ?
I will say yes!! But in the cases where we use Modern JavaScript classes and modules you can skip that because these features comes with the automatically enabled strict mode.
Note: It’s always preferred to use strict mode in all scripting file.It’s a good code practice.
Now all of you have the clear idea about "use strict"
.So let’s discuss about next new features of JS i.e nullish coalescing operator(??) and optional chaining(?.).
What is Nullish coalescing operator(??)
It is a new feature introduced in this ECMA proposal has now been adopted into the official JavaScript Specification.This operator returns the right hand value if the left hand value is null or undefined.
So first let’s understand what’s the problem we were facing that led to the development of the Nullish Coalescing Operator.
Before to handle null or undefined case we used if statement and conditional statement which is quite long and code quality is not that much good.
Suppose we have a school website where we listed all students details.In that we have to display the student firstName or lastName or lastName
.If all the data are undefined or null i.e display unknown
function getStudentName(firstName,lastName,nickName){if(firstName !==null && firstName !== undefined)
{ return firstName; }
else if(lastName !==null && lastName !== undefined)
{ return lastName; }
else if(nickName !==null && nickName!== undefined)
{ return nickName }return "unknown";
}
console.log(getStudentName(null,undefined,"XYZ")); //XYZ
You can see that it’s quite long and not that much clean to deal with such condition.
To tackle above problem, The OR ||
operator quite handy.OR operator works with logically true/false .It checks the left hand value if that is false then it will return right hand side value if left hand side true then it will return left hand side value.Let’s understand with above example.
function getStudentName(firstName,lastName,nickName){return firstName || lastName || nickName || 'unknown' ;
}
console.log(getStudentName(null,undefined,"XYZ")); //XYZ
It’s very short and clean code in compared to if
statement!!!😅
But the actual problems with OR operator ||
is that 0 and empty string ''
are logically false
by nature.And these value may change the expected behaviour of the program.Let’s understand the with an example.
Now in the school website that I've mentioned above , that also stores the student’s subject marks as well.If the student’s subject marks is available i.e. 0≤marks≤100 will display as it is.other wise display not appeared
.
function getMathMarks(marks){return marks || 'not appeared';}console.log(getMathMarks()); //not appeared
console.log(getMathMarks(100)); // 100
console.log(getMathMarks(0)); //not appeared
As you can see when we pass nothing or less than expected parameter it will treated as undefined i.e false so that will print correct not appeared
.similarly with 100 i.e true and print 100.But actual problem with 0 which is treated false and print not appeared
which is not correct result.
Nullish Coalescing Operator
So all the above problem, led to the development of the Nullish Coalescing Operator.The Nullish Coalescing Operator is defined by two adjacent question marks ??
In this case ,If the passed variable is either null or undefined and only if it’s those two values, the default value would be returned. In all other cases including 0, empty string, or false, the value of the variable is returned and not the default value.
function getMathMarks(marks){return marks ?? 'not appeared';}
function getStudentName(firstName,lastName,nickName){return firstName ?? lastName ?? nickName ?? 'unknown' ;
}console.log(getStudentName(null,undefined,"XYZ")); //XYZ
console.log(getStudentName(null,undefined,"")); //''
console.log(getStudentName()); //unknown
console.log(getMathMarks(100)); //100
console.log(getMathMarks(0)); //0
console.log(getMathMarks()); //not appeared
Note: The browsers supported by JavaScript Nullish Coalescing Operator are listed below:
- Google Chrome 80
- Edge 80
- Opera 67
- Safari 13.1
- Firefox 72
What is Optional chaining (?.)
The optional chaining ?.
is an error-proof way to access the nested object properties, even if an intermediate property doesn’t exist.
Let’s understand the problem first to understand the optional chaining.
Take the same student website as above,now in that we also store the address of the student in object forms which stores the details of city ,country etc.Now if you want to access that let’s see what happens when some details not available!!
function dispalyStudentAddress(studObj){console.log(studObj.address.city);
console.log(studObj.address.country);}const studentDetails1 = {address:{country:"INDIA"}}
dispalyStudentAddress(studentDetails1);
// output will be :
// undefined
// INDIA
But what will happen if address key will be not there and trying to key property of undefined.
const studentDetails1 = {};
dispalyStudentAddress(studentDetails2);output:
//Error:Cannot read property 'city' of undefined
it will throw error!! To solve that problem we have AND operator&&
. It’s check each required nested object property one by one and if that is available i,e true then only proceeds and print the actual available value but if that is not available i.e undefined
or null
means false then not proceed and will print undefined.
function dispalyStudentAddress(studObj){console.log(studObj && studObj.address && studObj.address.city);
console.log(studObj && studObj.address && studObj.address.Country);}const studentDetails1 = {address:{city:"XYZ"}}
const studentDetails2 = {};dispalyStudentAddress(studentDetails1); // XYZ undefined
dispalyStudentAddress(studentDetails2); // undefined undefined
Using AND operator in code for long nesting object decrease the code readability.Also it’s cumbersome to write.
To rescue from such problems Optional chaining (?.) comes into the picture.
Optional chaining (?.): It’s way to access the nested object property without any errors.It’s permit to reading the further nested value if the left hand side or variable before ?. is not
undefined
andnull
Let’s see above example with Optional chaining (?.).
function dispalyStudentAddress(studObj){console.log(studObj?.address?.city);
console.log(studObj?.address?.Country);}const studentDetails1 = {address:{city:"XYZ"}}
const studentDetails2 = {};dispalyStudentAddress(studentDetails1); // XYZ undefined
dispalyStudentAddress(studentDetails2); // undefined undefined
We can use it also to invoke the function and access array items and with expression.
let s1= {
msg() {
alert("I am a student");
},
name:"XYZ"}
let s2 = {};/* first Variable must exist before access with chaining*///1.FUNCTION CALL
s1?.msg?.(); // I am admin alert pop up
s1?.msg?.(); // undefined//2. Array items
const k1 = "name";
s1?.[k1] // XYZ
s2?.[k1] //undefined//3. Expression
let nestedProp = obj?.['prop' + 'Name'];
⚠ Don’t overuse the optional chaining
We should use ?.
only where it’s ok that something doesn’t exist.
For example, if according to our coding logic student
object must be there, but student
is optional, then student.address?.street
would be better.
So, if student
happens to be undefined due to a mistake, we’ll know about it and fix it. Otherwise, coding errors can be silenced where not appropriate, and become more difficult to debug.
Note: The browsers supported by JavaScript Optional chaining are listed below:
- Google Chrome 80
- Edge 80
- Opera 67
- Safari 13.1
- Firefox 74
I hope all the points has been cleared and got the better understanding of all above topics!! 😄
If you have any query related to these topics feel free to ask in comment section.And put your all valuable feedback!!!