Variable in javascript
- satyanarayan behera
- Aug 22, 2022
- 2 min read
In JavaScript variable means to provide a name to store the data. With the help of the variable, we can access the data and perform the operations.
In JavaScript we can declare the variable by the keywords var, let, and const.
currently, we are focusing on the var keyboard the below task is an example of that
Variable names are case-sensitive in JavaScript. So, the variable names msg, MSG, Msg, mSg are considered separate variables.
Variable names can contain letters, digits, or the symbols $ and _.
A variable name cannot start with a digit 0-9.
A variable name cannot be a reserved keyword in JavaScript, e.g. var, function, return cannot be variable names.
Variable stores data value that can be changed later on.
Variables can be defined using var keyword. Variables defined without var keyword become global variables.
Variables must be initialized before accessing it.
JavaScript allows multiple white spaces and line breaks in a variable declaration.
Multiple variables can be defined in a single line separated by a comma.
JavaScript is a loosely-typed language, so a variable can store any type value.
var name1; // declaring a variable without assigning a value
var name2 = 10; // declaring a variable with assigning a value
Tasks
Declare a new variable named petDog and give it the name Rex.
Declare a new variable named petCat and give it the name Pepper.
Console.log the petDog variable.
Console.log the petCat variable.
Console.log the text "My pet dog's name is: " and the petDog variable.
Console.log the text "My pet cat's name is: " and the petCat variable.
Declare another variable and name it catSound. Assign the string of "purr" to it.
Declare another variable and name it dogSound. Assign the string of "woof" to it.
Console.log the variable petDog, then the string "says", then the variable dogSound.
Console.log the variable petCat, then the string "says", then the variable catSound.
Reassign the value stored in catSound to the string "meow".
Console.log the variable petCat, then the string "now says", then the variable catSound.
var petDog = "Rex";
var petCat = "Pepper";
console.log (petDog);
console.log(petCat);
console.log("My pet dog's name is:",petDog);
console.log( "My pet cat's name is: ", petCat);
var catSound ="purr";
var dogSound ="woof";
console.log(petDog," says ",dogSound);
console.log(petCat," says ",catSound);
catSound = "meow";
console.log(petCat," now says ",catSound);
Output :
Rex
Pepper
My pet dog's name is: Rex
My pet cat's name is: Pepper
Rex says woof
Pepper says purr
Pepper now says meow
Comments