Skip to content

Clazariuk1/AlgoCasts

 
 

Repository files navigation

Interview Bank ( contains info from my interviews, interview courses from Grider, Steele, Traversy and others)

BTW to run tests

npm i
npm run test exercises/nameoffolder

note if you are in the exercises folder omit exercises and

npm run test nameoffolder

i.e. npm run test reverseint or npm run test exercises/reverseint

Concepts You Should Know How to describe ( Google and Stack Overflow)

  1. JavaScript Data Types
  2. Difference Between Const Let and Var
  3. Pass By Value vs Pass By Reference
  4. Map , Filter and Reduce ( Mutation or not)
  5. Falsey Values
  6. Global Variables
  7. This
  8. double equals vs triple equals
  9. Coercion
  10. typeof
  11. delete (not the http method)
  12. Object Notations
  13. Strict Mode
  14. Anonymous Functions
  15. Callbacks
  16. Closure
  17. instanceof
  18. IIFE
  19. HTML5 APIS
  20. Destructuring
  21. Rest and Spread
  22. Arrow Function differences
  23. HTTP Methods
  24. HTTP Status Codes
  25. HTTP 2 and HTTP 3
  26. Restful Routes
  27. Promises
  28. Async Await
  29. CSS Specificity
  30. Semantic HTML
  31. How do you make a Circle in CSS
  32. What is Z-index
  33. Vendor Prefixes Purpouse
  34. CSS Grid and Flexbox
  35. Speed Up a Slow App
  36. CRUD
  37. CRAP
  38. SOLID
  39. OOP
  40. Functional Programming
  41. Recursion
  42. SPA
  43. MPA

Notes on Functions


Title: Functions the First Frontier
Type: Lesson
Duration: 2hrs
Creator: Arthur Bernier Jr
Topics: Fun Fundamentals of Functions in JS

Functions

Lesson objectives

After this lesson students will be able to:

function

Explanation

Why Should I care about this I just want to know REACT

  • JavaScript Functions are incredibly versatile and in javascript they are what's known as first class citizens meaning they can be passed around like any other object.
  • Functions are literally objects in JS the same way Arrays are as you learned yesterday.
  • We will be using Functions everyday in JavaScript so you will learn more and more about them daily through repitition.

Setup

make a file functions.js

Test that a console.log will appear in Terminal when you run the file.

$ node functions.js

What is a function?

// 2 ways of creating functions

// function declaration
 	function one () {
   	  return 'one'
 	}
 	one()

 // function expression
 	const two = () => {
   	  return 2
 	}
 	const shotenedTwo = () => 2

Describe why we use functions

Using functions is another application of DRY. Don't Repeat Yourself. With a function, you can store code that can be used conveniently as many times as you wish, without having to rewrite the code each time.

Demonstration

Defining a function

const printBoo = () => {
	console.log('======');
	console.log('Boo!');
	console.log('======');
};

Always use const to declare your functions. It would be a strange day when a function would need to be reassigned.

The code will not run yet. The function needs to be invoked.

Invoke a function

Use one line of code to run multiple lines of code

printBoo();

Simply use the name of the variable and use parentheses to invoke the function.

If the parentheses are not included, the function will not run.

The invocation comes after the function definition. If you write it beforehand, it will be trying to invoke something that doesn't yet exist according to the interpreter.

This will work:

const printBoo = () => {
	console.log('======');
	console.log('Boo!');
	console.log('======');
};

printBoo();

VS

This will not:

printBoo();

const printBoo = () => {
	console.log('======');
	console.log('Boo!');
	console.log('======');
};

Imitation

Code Along

  • Write a function printSum that will console.log the result of 10 + 10

Extra Reps

  • Write a function printTriangle that will print these pound signs to the console (there are 5 console.logs inside the function):

     #
     ##
     ###
     ####
     #####
    
  • Make it so that printTriangle will print the pound signs using a for loop (there is a for loop and only 1 console.log inside the function).

  • Make it so that when you can invoke the function with the number of pound signs to print (not just hardcoded to print 5)

Properly name a function

The variable you use for a function should contain a verb. Functions do something, most often:

  • getting data
  • setting data
  • checking data
  • printing data

If the purpose of your function is to check data, for example, use the verb check in the variable name.

Example function that contains a conditional:

const checkInputLength = (input) => {
	if (input.length > 10) {
		console.log('input length is greater than 10');
	} else {
		console.log('input length is not greater than 10');
	}
};
  1. A Function name should always start with a verb
  2. A function if possible should be pure meaning it shouldn't effect anything outside of itself
  3. If it does effect something outside of itself you should let the resder of the function know that by the name for example we could have a function that checks if something is or isn't something
  4. we could also have a function that changes something or Mutates something like when you are playing a video game and you score a point, the function that updates the score could be called updateScore or setScore or changeScore
  5. Functions should try to do only one thing If a function, called checkInputLength, does more than just check input, then it is a poor function.
	// function that mutates
	const ricMershon = {
	age: 21
	}
	const scottDraper = {
	age: 25
	}
	
	const increaseAge = (person) => {
	  person.age += 1
	  console.log (`Horray it's your ${person.age} birthday`)
	}
	

Takeaway: Think about appropriate verbs to use in your function variable names. The verbs should indicate the one thing that the function does.

Write an arrow function with a parameter

The preceding function, checkInputLength had a parameter called input.

Functions can receive input that modify their behavior a bit. This input is called a parameter.

In the below example, the parameter is arbitrarily called name. We can call our parameters whatever we want - whatever makes semantic sense.

Using concatenation I can put the input into a string:

const sayName = (name) => {
	console.log('Hello! My name is ' + name);
}

When we invoke the function, we can specify the value of the parameter, this is called an argument:

sayName("Frodo");

We can continue to invoke the function with whatever arguments we want:

sayName("Merry");
sayName("Pippin");
sayName("Sam");

Each time, the output of the function will change to reflect the argument.

Argument vs Parameter

The argument is the input, the parameter is how the input is represented in the function.

const func = (PARAMETER) => {
	// some code
}

func(ARGUMENT);

Write an arrow function with multiple parameters

A function can take any number of parameters.

const calculateArea = (num1, num2) => {
	console.log(num1 * num2);
}

When you invoke the function, you generally want to supply the right number of arguments.

calculateArea(4, 4)

=> 16

How does this work? Aka (The Execution Context Interview Question Answer)

let myNum = 2;

const square = (num) => {
	return num * num
}

so in our code we have now created a variable myNum on line 1 that is equal to 2 and then created a variable called sqaure that is equal to the function we created.

JavaScript does 3 super awesome things that makes it a great very first programming language, and that makes it elegant enough to be used by developers with decades of experience.

We will go over those things as we go through this course but what pertains to us is the awesome feature of the JavaScript being single threaded and reading code line by line and executing code only when you ask it to.

So in JS when it comes to what's running in our code we are never too confused if we remember JS goes line by line and 1 at a time.

And we keep track of this in what's called our Execution Context js engine 1

So when the JS Engine looks at our code it will start at the top and perform each operation line by line

js engine 2

let myNum = 2;

const square = (num) => {
	return num * num
}
const ans = square(myNum)

js engine 3 updated

So as you can see when we call a function we go ahead and add it to the stack of things that we want JS to do. Once JS has finished that task it goes back to the main code on the next line and runs again.

So once square has completed running it will give us a value and assign it to ans

let myNum = 2;

const square = (num) => {
	return num * num
}
const ans = square(myNum)
console.log("Hello World")

what order will this happen

let myNum = 2;

const square = (num) => {
	return num * num
}
console.log("Hello World")
const ans = square(myNum)

what about this?

Break a problem down into steps

Write a function that will return true if a word is a Palindrome, or will return false if not.

  • Problem solve one step at a time
  • Each step might require research

Work in layers, one layer at a time. Don't jump ahead until each piece has been tested and works.

Determine if each step will require research, and research it.

  • reverse the word (how?)
  • check if the word is the same as the reverse (how?)
  • return true or false
	// --- Examples:
	//   palindrome("racecar") === true
	//   palindrome("abcdefghijklmnop") === false

Practice

Exercises

  • Write a function called square that takes in a number and squares it and then assign the result to variable called ans

     	square(5); // 25
  • Write a function called minusOne that takes a parameter num. Assuming the argument is a number, print the argument -1.

     minusOne(10);        // 9
     minusOne(100);       // 99
     minusOne(Infinity);  // Infinity
  • Write a function makeSentence that takes three parameters and concatenates them into a fully formed sentence.

     makeSentence('I', 'want', 'chimichangas');

    => 'Oh boy, do I want chimichangas or what?'

Extra

  • Write a function called getLastElement that takes a parameter arr.

  • Invoke the function with an array as the argument.

  • The function should print the last element within the array.

     getLastElement([1, 2, 3, 4, 5, 6]);       // 6
     getLastElement(['a', 'b', 'c']);          // 'c'
     getLastElement([[1, 2, 3], [4, 5, 6]]);   // [4, 5, 6]

    Hint: arr[arr.length - 1]

Extra

  • Write a function divideThreeNums that takes three parameters and prints the third parameter divided by the result of the second parameter divided by the first.

     divideThreeNums(10, 5, 2)   // 4
     divideThreeNums(30, 2, 9)   // 135

Exercises ( aka example whiteboard questions for junior devs)

  • Write a function that accepts a string. The function should capitalize the first letter of each word in the string then return the capitalized string.
	// --- Examples
	//   capitalize('a short sentence') --> 'A Short Sentence'
	//   capitalize('a lazy fox') --> 'A Lazy Fox'
	//   capitalize('look, it is working!') --> 'Look, It Is Working!'
  • Write a function that takes three parameters (numbers), sums them, converts the sum into a string and returns the string (eg. "123")

    • Use your google-fu to research converting a number into a string
    • Invoke the function a couple of times with different arguments each time
  • Experiment

    • What happens if you supply more arguments than there are parameters?
    • What happens if you supply fewer arguments than there are parameters?

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 83.2%
  • HTML 13.6%
  • Python 2.7%
  • CSS 0.5%