variable function 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: how to write a variable in js

//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

Example 3: variable javascript

//You can make a variable by using:
var variable-name = 'defenition of the variable';
// Or you can use
let variable-name = 'defenition of the variable';

Example 4: how to define variable in javascript

var <variable-name>;

var <variable-name> = <value>;

Example 5: how to declare a variable js

//let and var are both editable variables and can be changed later on in your program;
let dog = 'Woof';
//dog is equal to the string 'Woof';
dog = false;
//You can changed the value of dog now because it was defined with let and not const;

let cow = 'Moo';
//cow is equal to the string 'Moo';
cow = true;
//You can change the value of cow later on because it is not defined with const;

//const is used when declaring a variable that can't be changed later on -- const stands for constant;
const pig = 'oink';
//This assigns the string 'oink' to pig which can not be changed because it is defined with const;
pig = 'snort';
//Above throws an error
//Good Job you now know how to declare variables using JavaScript!!!

Example 6: javascript function

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
// FUNCTION DECLARATION (invoking can be done before declaration)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
function calcAge1(birthYear) {
   return 2037 - birthYear;
}
const age1 = calcAge1(1991);

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
// FUNCTION EXPRESSION (invoking canNOT be done before declaration)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
const calcAge2 = function (birthYear) {
   return 2037 - birthYear;
}
const age2 = calcAge2(1991);

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
// ARROW FUNCTION (generally used for one-liner functions)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
const calcAge3 = birthYear => 2037 - birthYear;
const age3 = calcAge3(1991);
console.log(age3);