Fundamentals Of Javascript

Data types, logical operators, if statements and for loops

 

Halah Al-Shaikhly

https://slides.com/halahsalih-1/fundamentals-of-javascript

Objectives

  • Dynamic Typing 
  • Data Types
  • Operators
  • Conditional Statements
  • Loops

Set up your environment

We’re about to begin writing code, so we can choose either of these :

  • Open sublime text editor, atom text editor or

  • Open Repl. https://repl.it/languages/javascript_web

  • Open developer’s tool on your chrome/firefox browser using this command (command + shift + j or sometimes i). Or Right click anywhere on your browser’s window and click inspect and click on the console tab.

  • If you’re using windows PC or/and IE .. download chrome and use it to order a new MacBook.  

  • IE: Open Tools -> Developer Tools

  • Safari : Develop -> Show web inspector

Dynamic Typing

javascript is a dynamic programming language

you don't have to declare the type of variable ahead of time.

The data type will be determined when the program is being processed. 

The type will change based on what kind of data the variable is holding. 

Flexible.

Dynamic Typing

To declare a variable, you use the statement var

var x = 33; 

 

// note how there is no type specified as the variable is declared. 

x can hold any type of value at any time

Static Typing

Some programming languages declare variables to hold a specific type of data. 

it prevents unintended value conversions

examples of static programming languages: C, C++ 

int x = 0; // specified that this variable holds integer values only

Data types

  • Number
  • String
  • Boolean
  • Undefined
  • Null
  • Symbol (new)
  • Object

Number

  • it can hold integers

  • var x = 3;

  • it can hold floating points

  • var x = 3.45;

  • it can be negative or positive

  •    var x = - 4.89;

Typeof

Javascript provides a typeof operator that examines a value of a variable and tells you what type it is

 

var x ;
console.log(typeof(x)); 

// it can be used as typeof x;

x = 2;
console.log(typeof(x));

 

x = 3.4;
console.log(typeof(x));

 

Data types

  • Number
  • String

String

  • Represents textual data
  • Each element is a character
  • Spaces count
  • The first element is at index 0, the next at index 1, and so on
  • ​Text must be inside quotation marks.

var school = 'Galvanize';

concole.log(school[0]); // G 

String example

  • var firstName = 'Bella';
  • var someName = 'Bella ';

 

these two values are not the same. 

'Bella' has a length of 5 while 'Bella ' has a length of 6. 

Spaces count

Length of String

length is a property of a string.

It counts the number of elements or characters in a string.

var name = 'My name is bond';

console.log(name.length);

String: Exercise time

Find the length of the following strings

var name = 'James';

 

var y = '  ';

 

var x = ' ';

 

var name2 = 'James_Bond';

hint: use console.log() to print the length to the console.

Google mdn javascript String

This is not a joke

create  a variable to holds your name

make all the letters upper-case using a method

make all letters lower case using a method

Data types

  • Number
  • String
  • Boolean

Boolean

  • it represents logical values.
  • it can have two values only.
  • either true or false.

var b = true;

var c = false;

a boolean value is another way of representing a yes or no answer, or 0 or 1. 

Data types

  • Number
  • String
  • Boolean
  • Undefined

Undefined

when a variable doesn't have a value assigned , the type of the data in that case is undefined.

var y ;

 

console.log(typeof y);

Data types

  • Number
  • String
  • Boolean
  • Undefined
  • Null

Null

var a = null;

typeof null // 'object'

Null is a special kind of object. 

null is when variable doesn't have a value.

Null

a variable doesn't have a value. 

Undefined

variable doesn't have a type. 

Data types: exercise time

var a;

a = "hello world";

a = 42;

a = true;

a = null;

a = undefined;

 

determine the data type of the following variables

use typeof

Data types

  • Number
  • String
  • Boolean
  • Undefined
  • Null
  • Object

Object

  • Object is a compound value. 
  • it is a collection of properties.
  • each property is a pair of keys and values.
  • the keys are like variable names.
  • the values could be any data type(everything we had mentioned before,including objects!)
  • the pairs are separated by a comma.
  • one of the most useful value types in all of JavaScript.

Object: Syntax

var a = {}

// the curly braces are called an object literal

// this is an empty object

var obj = {
    a: 1.47,
    b: 1,
    c: true,
    d: 'Hello World'
};

example

Object: Syntax

var a = {
            b: 1,
                 c: true,
                                d: 'Hello World'
};

keys

values

 

Object: Syntax

How can you access the object properties? 

 

Can you modify their values? 

How can you add properties to the object?

You can access the object properties using three ways:

Dot Format

obj.b;

var obj = {
    a: 1.47,
    b: 1,
    c: true,
    d: 'Hello World'
};

bracket notation

obj['b'];

Object: Synatx

variables

var someKey = 'e';

obj[someKey];

// declare an object
var obj = {}; // this is an object literal
console.log(obj);

// you can also declare an object with values like this
var obj2 = {
    x:2,
    y:'hello!'
}

// add property to obj
obj.a = 'yo yo hommie';
obj.b = 10;
console.log(obj);

//modify property to obj
obj.b = 56;
console.log(obj);

//access property
console.log(obj.a); // dot notation
console.log(obj['a']); // bracket format

var someKey = 'h';
obj[someKey] = false; // variable
console.log(obj);

// anything can be the value of key
obj.newKey = {
    tt:1,
    o:true
    };

console.log(obj);

Objects : Exercise time!

create an object named person, add keys to store your first name, last name, age, your mother's maiden name, social security number, ATM pin and email it to hacker4Life@yahoo.com

var person = {};

person.firstName = 'Halah';
person.lastName = 'Al-Shaikhly';
person.age = 26;

console.log(person);


Other Data types 

  • Arrays.
  • Functions. 

These data types are special version of the object type. 

Arrays

  • array is an object.
  • it hold any kind of values
  • instead of having properties(keys & values), arrays have items ,they hold them in a numerically indexed positions. 
  • Items are separated by a comma. 
  • Each item in array has an index
  • Indices start from 0. 

var arr = [];

// this is how you declare an empty array

Arrays : Example

var arr = [
    "hello world",
    42,
    true,
    {a :1, b:'yo'}
];


console.log(arr);

arr[0]; // accessing index zero
arr[1]; // accessing index 1

arr.length; // what is length?

typeof arr; // what is the result of this?

Data types, properties  exercise

make an array named dogs, it has 3 items. Each item is a dog and each dog has a name, age and  whether or not they like cats.  

Print the last dog's age. 

Hints

  • each dog might be an object ..
  • that object might have properties .. 
  • liking   a cat property could be of type boolean .. 

Solution

var dogs = [
    { name : 'Marry', age: 9, likesCats: false},
    { name : 'Kommie', age: 4, likesCats:true},
    { name : 'Bacon', age: 2, likesCats:false}];
    
console.log(dogs.length);

//log the the last dog age only
console.log(dogs[2].age);

Functions

"a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value."

  • In Java script functions are objects
  • They can have properties and methods just like any other object.
  • A function always returns a value.

Functions: Declaring a function

function functionName(param1,params2 , ....){
    //statements
}

function

it is the key word to declare a function

functionName

this could be f1, haha, anything

params

values passed to the function

statements

any statement

Functions: Example

How to declare a function

// function being declared
function myFunction(){
}

// how to call a function

myFunction();
function myFunction2(){
}

console.log(myFunction2());
function myFunction3(){
    
return 1;
}

console.log(myFunction3());

Functions: Example

How to can I pass data to a function?

function f1(x){
    console.log(x*x);
}

f1(3);
//pass multiple data
function f2(x, y){
    
    console.log(x*y);
}

f2(3,5);
//what happens if I send one value only? 
f2(3);

//let's try a return statement
function f3(x){
    return x *3;
}

console.log(f3(4));

Functions: Excercise

How to can I pass data to a function?

function f7(x){
    console.log(x*x);
}

// what will be the result here? why?
console.log(x);

var y = 8;
function f8(){
	y = 9;

}
// what is the output of this? 
console.log(y);
//how about now, why?
f8();
console.log(y);

Functions: Q & A

Can I pass other datatypes to a function?

what other datatypes I can pass?

can I pass a function to another function as parameter?

Can a variable hold a function?

What's an anonymous function?

Functions: Q & A

//takes an array as a funcion argument
function printData(data){
	console.log(data);
}
//passing an array
printData([1,2,3]);
//passing an object
printData({
	a:1,
	b:2
});

function sum(x,y){
	return x +y;
}

//passing a function
printData(sum(1,2));

// anon function is a function without a name
var p = function(){
	console.log('I have no name. I\'m an anon function');
	return 4;
}

function h(f){
	console.log('im inside h');
	console.log(f());
}

h(p);

Operators

operators perform actions on variables and values.

  • Assignment operator: var a = 10;
  • Math operators +,-,*/ .. var b = a * 20;
  • Equality operators: ==,!=,===,!== (evaluate to true or false)
  • Comparison operators <, <=, >,>= (evaluate to true or false)
  • Logical operators: && (and) || (or). These operators are used to express compound conditionals.

Operators: Example

var a = 10;

var b = 6;

// math operator
var c =  a + b;
console.log(c);

// comparison operators
var d = a > b;
console.log(d);

var e = a <= b;
console.log(e);

//equality
var f = a === c;
console.log(f);

var g = a !== c;
console.log(g);

//logicals
var h = f && e;
console.log(h);

var i = g || h;
console.log(i);

control flow/ conditional statements

  • they're statements that determine which part of the code will execute. 
  • they determine that based on conditions
  • these conditions evaluate to either true or false
  • equality, comparison and logical operators .. yey.
  • if you're not using equality,comparison or logical operators, then JS tried to determine whether the condition is truthy or falsey.
  • example of conditional statements: if statements.

If statement

 They tell JS which statements to execute, based on a condition.

// syntax
if (condition){
// statements to be executed.
}

//example

var b = 23;

if (b > 20) {// evaluates to true
    console.log('condition is met');
}

if(b > 20 && <= 23){
    console.log('b is between 20 and 23');
}

Truthy & Falsy Values

if you're not using equality, comparison or logical operators in a condition, then javascript tries to determine wether this condition/value is truthy or falsey.  

Truthy value is everything else. All values are truthy unless they're defined as falsey.

Falsey value is a value translated to false when evaluated in a boolean context. 

Falsey Values

  • number zero
  • empty string ""
  • false
  • undefined data type
  • null data type
  • NaN

everything else is a truth value.

Turthy & Falsey : Example

var someValue = true;

if(someValue){
    console.log('this is a truthy value, condition is true');
}

if(0){
    console.log('this is a false value, condition is false');
}

if(''){
    console.log('empty string is a false value, condition evaluated to false, 
    statement will not be executed');
}

// will the following statement inside the curly brackets be executed? why?

var z;
if(z){
    console.log(z);
}

if(null){
console.log('yo');
}

if else statement

if the condition(s) in the if statements are not met, execute other statements

var b = 10;

if(b < 5){
    console.log('b is less than 5');
}
else{
    console.log('b is greater than 5');

}

if /else if/else statements

for multiple conditions

var b = 5;

if(b < 5){
    console.log('b is less than 5');
}
else if(b > 5){
    console.log('b is greater than 5');

}
else{
      console.log('b equals 5');
}

Conditional statments: Exercise time

declare two variables, give them values of your own choice and write some statements to determine if one the values is greater than or equal the other value.  Print the result to your console.

Hints

  • use console.log to print results
  • use if/else if/else

Solution

var x = 40;

var y = 89;

if( x > y){
    console.log('x is greater than  y')
}
 else if(x < y) {
    console.log(' y is greater');
}

else{
    console.log('x and y are equal');
}

Iterations & Loops

Loops are a way to do something repeatedly

all loops repeat the same action several times.

Iterations & Loops: Types

  • For loops
  • do while loops
  • while loops
  • for in loops

Iterations & Loops: For Loops

for(var i = 0; i < 5; i++){

    console.log('I\'m a statment running for i= '+ i);
}

use the keyword for to start a for loop

initial expression

the condition. this where you determine how many times the action is repeated

incremental expression

Statement or action to be repeated till condition is false

The end. 

Halah Al-Shaikhly

@twiter: halinaSalih

@email:halah.alshaikhly@gmail.com

@github:halahRaadSalih

Fundamentals Of Javascript

By Halah Al- Shaikhly

Fundamentals Of Javascript

  • 1,139