Introduction to Functions in JS

I Meet the Functions

i. Introduction 1/13

var speed = 65;
if (speed > 80 ) {
	console.log("Slow down");
} 
else {
	console.log("Drive safe")
}

ii. Introducing Functions 2/13

var divideByThree = function (number) {
    var val = number / 3;
    console.log(val);
};

divideByThree(8);

iii. Function syntax 3/13

var greeting = function (name) {
    console.log("Great to see you," + " " + name);
};

// On line 11, call the greeting function!
greeting("Sunakshi");

iv. How does a function work? 4/13

var foodDemand = function(food) {
    console.log("I want to eat" + " " + food);
}
foodDemand("dosa")

v. Tying it all together 5/13

var calculate = function (number) {
    var val = number * 10;
    console.log(val);
};

// Badly written function with syntax errors!

var greeting = function (name) {
    console.log("Hey brother!" +" " +name);
} 
greeting("Saksham")

II Functions and Return
i. Don’t Repeat Yourself (D.R.Y) 6/13

var orangeCost = function(price) {
    console.log(price*5);
}
orangeCost(7)

ii. Return keyword 7/13

var timesTwo = function(number) {
    return number * 2;
};

timesTwo(8);

// Call timesTwo here!
var newNumber = timesTwo(8);
console.log(newNumber);

iii. Functions, return and if / else 8/13

II Functions and Variables

i. Functions with two parameters 9/13

var perimeterBox = function(length,width) {
    return 2*(length + width);
}

perimeterBox(5,6)

ii. Global vs Local Variables 10/13

var timesTwo = function(number) {
     var my_number = number * 2;
    console.log("Inside the function my_number is: ");
    console.log(my_number);
}; 

timesTwo(7);

console.log("Outside the function my_number is: ")
console.log(my_number);

iii. Functions recap 11/13

var nameString = function (name ) {
   return "Hi, I am" + " " + name;
}
console.log(nameString("Sunakshi"));

iv. Functions & if / else 12/13

var sleepCheck = function(numHours) {
    if (numHours >= 8) {
        return "You're getting plenty of sleep! Maybe even too much!";
    }
        else {
            return "Get some more shut eye!";
        }
}
        
sleepCheck(10)
sleepCheck(5)
sleepCheck(8)

v. Conclusion 13/13
Save and Submit!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s