Variable mutation and type coercion in Javascript
In this chapter, you will learn about Variable mutation and type coercion in Javascript. Let’s consider the below code snippet,
let actor = 'John'; let actroBirthYear = 1973; let isProducer = true; let nationality = 'American'; console.log('The'+' '+actor+' '+'is an'+' '+nationality+' '+'actor, And birth year is :'+actroBirthYear+', Is producer :'+' '+isProducer); // // output // // The John is an American actor, And birth year is :1973, Is producer : true
As we can see the output in console of the above code snippet, the output is a complete string and the understand the type variables which we used in the code snippet
- The Variable actor type is: String
- The Variable actorAge type is: Number
- The Variable isProducer type is: Boolean
- The Variable nationality type is: String
Even when the Variable actorAge is a Boolean and isProducer is Boolean, the Javascript is writing the string into the console. Here all kind of Variables been converted to the string. This works with the help of type coercion in Javascript.
What is type coercion in Javascript?
The process that Javascript automatically converts types of Variables to another type when it is needed.
What is a variable mutation in Javascript?
Javascript allows changing the value of a variable anywhere in the program. We can define the multiple variables in the same line and values can be assigned later. The Values of the Variables can be redefined. Let’s see the below code snippet
Variable mutation: Variable mutation in Javascript allows to change the value of a variable.
let actor, actroBirthYear, isProducer, nationality; console.log(actor); console.log(actroBirthYear); console.log(isProducer); console.log(nationality); // output // undefined // undefined // undefined // undefined actor = 'John'; actroBirthYear = 1990; isProducer = true; nationality = 'Indian'; console.log(actor); console.log(actroBirthYear); console.log(isProducer); console.log(nationality); // output // John // 1990 // true // Indian actor = 'Mickel'; actroBirthYear = 1995; isProducer = false; nationality = 'UK'; console.log(actor); console.log(actroBirthYear); console.log(isProducer); console.log(nationality); // output // Mickel // 1995 // false // UK
As you can see in the above code snippet, the 4 variables actor, actroBirthYear, isProducer, nationality is been declared in the same line. Later we assigned the value as
actor = 'John'; actroBirthYear = 1990; isProducer = true; nationality = 'Indian';
And later we assigned a new value
actor = 'Mickel'; actroBirthYear = 1995; isProducer = false; nationality = 'UK';
One thought on “Variable mutation and type coercion in Javascript”
Comments are closed.