Master Basic JavaScript

Master Basic JavaScript

History of JavaScript

  • JavaScript was created in 1995 by the Netscape web browser. It was a way for them to be able to add actions to websites.

  • Every browser had its idea of what JavaScript was. So there was no standard. Eventually, a standard had to be created to ensure everyone had the same idea of what JavaScript was. So that web developers can build one website and have it work on all browsers. This standard was called ECMAScript.

JavaScript Types

JavaScript has 7 types /values javascript accepts

  1. Number: JavaScript accepts numbers.

    Example:(3+4,12/4,8%2...)

  2. String: is just a text and to let javascript know it is the string you have to write it inside double quotes or single quotes.Example: "triumph"

  3. Boolean: means true or false

  4. Undefined: this means the variable has not been assigned to anything

  5. Null

  6. Symbol (New in ECMAScript 6)

  7. Object

JavaScript Comparissons

  • != (Not Equal) (!== not equal value or not equal type)

  • \== (Equal tp) (=== equal value and equal type)

  • \>= (greater than or equal to)

  • <= (Less than or equal to)

  • \> (Greater than)

  • < (Less than)

JavaScript Variable

  • var

  • let(new in ECMAScript 6)

  • const(new in ECMAScript 6)

Variables

  • To catch and hold values javascript has variables, and it can be used with the word var.

  •             var javaScript ="The coolest language!";
                Console.log(javaScript);
    
  • = means to assign value

  • A variable can't start with a number, a variable can start with a letter and can end with a number.

  • A variable can start with a $ or an _

  • The variable can hold any JavaScript type.

  • You can reassign a new value

    JavaScript Conditionals

    Conditional Execution or Control Flow

    • if

    • else

    • else if

    • ternary operator

    • switch

if statement

Use the if statement to specify a block of JavaScript code to be executed if a condition is true.

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error.

if (condition) {
  //  block of code to be executed if the condition is true
}
var name = "Lucas";
if (name==="Lucas"){
    alert("Hi Scott");
   }

else statement

  • Use the else statement to specify a block of code to be executed if the condition is false.
if (condition) {
  //  block of code to be executed if the condition is true
} else {
  //  block of code to be executed if the condition is false
}
var name = Haley;
if (name==="Lucas"){
    alert("Hi Scott");
   }else {
   alert("You are not a Scott");
}

else if

  • Use the else if statement to specify a new condition if the first condition is false.

      if (condition1) {
        //  block of code to be executed if condition1 is true
      } else if (condition2) {
        //  block of code to be executed if the condition1 is false and condition2 is true
      } else {
        //  block of code to be executed if the condition1 is false and condition2 is false
      }
      var name = "James";
      if (name==="Lucas"){
          alert("Hi Scott");
      }else if (name==="Nathan"){
          alert("Hi Scott");
      }else {
         alert("Sorry!!You are not a Scott");
      }
    

JavaScript Logical Operators

  • && (and)

  • || (or )

  • ! (not)

//                && (and) 
var firstName = prompt("First Name");
var lastName = prompt("Last Name");
if (firstName === "lucas" && lastName==="nathan"){
    alert("welcome scott");
}else{
alert("i dont know you");
}
//                ||(or)
var name = prompt("Enter your name");
if (name === "lucas" ||name==="nathan"){
    alert("welcome scott");
}else{alert("i dont know you");}
//                 !(not)
var name = "billy";
if(!(name==="nathan" || name==="lucas"))
    alert("not a Scott family");
else{
    alert("Scott family member");
}
// !true= false        !false= true

Function

  • Functions are the main “building blocks” of the program. They allow the code to be called many times without repetition.

  • We’ve already seen examples of built-in functions, like alert(), and prompt(). But we can create functions of our own as well.

  • So with functions, we have 2 options. One - is using existing JavaScript functions, like 'alert' and 'prompt'.And two - we can create our own.

  • () means to execute the function. To run a "function" alert I execute it by calling it like this alert() So, these brackets() mean 'calling a function', so I can call a function.

  • When we don't return something we get undefined and when we return something we get value

    when we don't return something we get undefined

  •       alert("hi");  //lets break it down
          // alert → function
          // () → calling an alert function
          // "hi" → calling an alert function with an argument "hi"
    
  • Function parameters are the names listed in the function definition

      function sing (playlist){
          alert(playlist);
      }
      sing("Ilahy Aenni");
      sing("Ilahy Asiron");
      sing("Taweel");
    
  • Function arguments are the real values passed to (and received by) the function. And we can have multiple arguments by just adding a comma.

  • Arguments allow us to not repeat ourselves and make our functions what we call more extensible.

  •       console.log("hi");   // "hi" is a argument 
          console.log("hi", "how are you") // multiple arguments
    

JavaScript Functions

  • var a = function name() {} (Function Expression/ Anonymous function)

  • function name() {} (Function declaration)

  • return

  • () => (new in ECMAScript 6)

Function Expression

var greet = function(){
    console.log("hello");
}
greet();

Function declaration

function greet(){
    console.log("bye");
}
greet();
//Example 2
function multiply(a,b){
    return a*b;
}
multiply(4,19);   //answer 76

Return

The return statement stops the execution of a function and returns a value

function multiply(a,b){
  return a;
  return a*b;
  return b;
multiply(44,99);   // answer 44
//Example 2
function multiply (a,b){
    if (a>10 || b>10){
        return ("it's too big");
    }else{
        return(a*b);
    }
}
multiply(3,4);      //answer 12

A function is a variable

var c = function(a,b){
      if (a>10 || b>10){
          return "too big";
      }else{
          return a*b;
      }
}
c(8,9);      //72
c(10,9);     //90

Inner Function

function multiply (a,b){
   return a*b;
}
alert(multiply(3,4));

Data Structure

Array

  • An array is a special variable, which can hold more than one value

  • An array can hold all javascript types e.g: number, boolean, function, etc

  • We can make arrays within an array

  • Position of an element is called index

//how to make an array
var list = ['soap','toothpaste','bread','pasta','rice']
//how to display the entire list on the array
console.log(list);
//how to grab an item from the list
console.log(list[1]);
//multi-list
var multiList = [
    ["dumble","barbell","t-bar"],
    ["bread","cake","eggs"]
]
console.log(multiList);
//grab eggs from the list
console.log(multiList[1][2]);

JavaScript Array Methods

  • Add, remove and sort items.
var force =["spring","friction","resistance","tension","applied"];

//To add items to the end "push"
console.log(force.push("gravitatonal"));
//To extract an item from the end "pop"
console.log(force.pop());
// To extract an item from the beginning "shift"
console.log(force.shift());
// To add items to the beginning "un-shift"
console.log(force.unshift("spring"));
//To sort an array
console.log(force.sort());
  • Splice and Slice

  •       //slice
          //It returns a new array copying to it all items from index start to end (not including end). 
          console.log(force.slice(1,3));
          //splice
          console.log(force.slice(1,4));
          //1 is the start point 4 is the count value, how many should it count.
          console.log(force.slice(1,4,"sup"));
          //delete 4 items from the start point and add "sup".
    
  • Concat

  •       //The method creates a new array that includes values from other arrays and additional items
          var force =["spring","friction","resistance","tension","applied"];
          var newForce = force.concat(["electromagnetic","gravitational"]);
    

Objects

  • Objects are collections of properties.

  • Second data structure and 7th javascript type.

var car={
    name: "volvo",
    model: 500,
    weight:850,
    color: "red",
    new: false,
}
// property = name ; value = volvo;

//how to grab
console.log(car.name);
//how to add  "Method"
car.new = true;
car.drive= "running";

Methods of Objects

  • A function inside an object is a method
var user={
 name: "Mandy",
 age: 32,
 hobby:"Swim",
 shout: function(){
    console.log("yellllll!");    
}
};
//to grab shout "function"
user.shout()
//shout is a method of user
//console.log → console is just a object and log is a method

Array inside an object

var user = {
name:" Sam",
age: 21,
class: "BTECH",
isMarried: false,
hobby:["swimming","skating","boxing","coding"],
};
//how to grab the array
user.hobby
//how to grab the item inside an array
user.hobby[1];

Objects inside an array

var userList =[
    {
      username: "billy",
      password: "secret",
     },
     {
     username: "jim",
     password:123,
     }
];
//how to grab
list[0].password;

Null

  • The value null represents the absence of any object, while the empty string is an object of type String with zero characters
//we can have an empty list and empty object
var emptyObj ={}
→  undefined
var nullObj =null;
→  undefined
emptyObj
→  {}
nullObj
→  null
//i can't set a property in a null object
nullObj.name="spoon";
→  it will return an error
//i can add a property in empty object
emptyObj.name="spoon";
→  "spoon"

Loops

  • For loop
var todos=[
"clean room",
"brush teeth",
"exercise",
"study",
"eat"
];
//if we want to Add "!" in all items
for(var i=0; i<todos.length; i++){
 todos[i]=todos[i]+ "!";
}  
//.length tells us how many items in the list
//if we want to Delete items in list
var todosLength =todos.length;
for(var i=0; i<todos.length; i++){
 todos.pop();
}
  • While Loop
var counterOne =0;   //counting of number
while(counterOne < 10){
console.log(counterOne);
counterOne++
}
var counterOne =10;   //count down
while(counterOne >0){
console.log(counterOne);
counterOne--
}
  • do while
var counterTwo =10;   
do{
console.log(counterTwo);
  counterTwo--;
}while(counterTwo > 0); //we give a condition here

forEach

Difference between for loop and forEach

var todosLength =todos.length;     //for loop
for(var i=0; i<todos.length; i++){
 console.log(i);
}  
todos.forEach(function(i)){     //forEach
console.log(i);
})