how to assign variables in javascript code example
Example 1: javascript declare a variable
//choose the best for your solution
var myVariable = 22; //this can be a string or number. var is globally defined
let myVariable = 22; //this can be a string or number. let is block scoped
const myVariable = 22; //this can be a string or number. const is block scoped and can't be reassigned
Example 2: add variables in javascript
var a = 5;
var b = 2;
var c = a + b;
Example 3: how to create variables using javascript
var myVar; //unitialized variable( can be intiallized later )
var number = 1; //number
var string = " hello world " ; //string
var boolean = true ; //boolean
myVar = function(){ //variable can hold function
};
Example 4: how to make a variable equal a specific element in javascript
//How to make a variable equal a specific element in javascript.
/*====DESCRIPTION STARTS HERE=======
Assuming you've already created an array and a variable, you simply set the
variable equal to the array, specifying the specific location of the value
it holds. Note though that when specifying the location, subtract one
number from the actual number we percieve. The reason for this is that computers
begin counting at 0.
=====DESCRIPTION ENDS HERE========*/
//=====EXAMPLE=========
var listOfFirstNames = ["Will", "Kotori", "Grace", "James"]
var FirstName = listOfFirstNames[2] /*firstName now has the value of "Grace"
since grace is the 2nd (or 3rd) element
of the array*/
Example 5: how to assign variables in javascript
// data from json: resp = {"home": 1, "landmark": 2}
// Method 1:
// use ` for add variable
url = `workspace/detail/${resp.home}`;
console.log(url) -> // workspace/detail/1
// Method 2:
// use ' and + for concentrace variable
url = 'workspace/detail/' + resp.home;
console.log(url) -> // workspace/detail/1