Basics of JS
Variable Declaration:
var myVariable = "David";
var myNumber = 300;
PopUp Window
alert(myVariable);
Input Box
prompt() //alert with input box
Console
console.log('this is a log to console:', myNumber)
Assignments
var name = 'Guy' , age='46';
var age1 = 30, age2 = age1 + 4
When a variable is not defined -
Uncaught ReferenceError: age1 is not defined
When a variable was called before it was defined
undefined
A variable can change its type in runtime
var foo = 42; // defined as a number
foo = 'guy'; // now its a string
foo = true; // not its a boolean
Remarks (like c)
// single line
/*
- range-multiline
*/
Operators
regular + - * /
comparison === Type and Value (77 === '77' -> false)
comparison == Value only (77 == '77' -> true)
not !
not equal !===
maths x += y x = x + y
x -= y x = x - y
x *= y x = x * y
x /= y x = x / y
reminder x%=y x = x % y
exponent x**=y x = x ** y
Logical Operators
Operator |
Usage |
description |
Logical AND (&&) |
exp1 && exp2 |
Only if both are TRUE |
Logical OR (||) |
exp1 || exp2 |
at least one of them is TRUE |
Logical NOT (!) |
!exp |
is not TRUE |
Precendence |
ex1 && ex2 || ex3 && ex4 |
AND checked before OR |
Text concatenation
console.log('guy' + ' ' + 'and ' + 'Natasha' )
Conditions
if(something === something ){
}else if{
}else{
}
Ternary Operator
a short way to write a condition
var beverage = (age >= 21) ? "Beer" : "Juice";
var resultHolder = (condition) ? TRUE value : FALSE value;
- Definition of variable beverage
- Checking a condition (with a different varible in this case)
- ?
- What to return if TRUE
- :
- What to return if FALSE
- ;
the new variable will contain one of the strings
With multiple conditions:
var resultHolder = (condition) ? value1
:(condition) ? value2
:(condition) ? value3
:value1;
Functions
// Define function
function myFunction(arg1,arg2){
var result = arg1 * arg2;
return result;
}
Call the function
myFunction(var1,var2);
back to main page