Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4K views

Java Script 101

This document provides an overview of basic JavaScript concepts including data types, variables, functions, arrays, and operators. It defines key terms like parameters and arguments. The document also explains JavaScript syntax like comments, semicolons, and operators. Core array methods are described like .push(), .pop(), and .shift(). Conditionals and comparison operators are also summarized.

Uploaded by

amandajbatts
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4K views

Java Script 101

This document provides an overview of basic JavaScript concepts including data types, variables, functions, arrays, and operators. It defines key terms like parameters and arguments. The document also explains JavaScript syntax like comments, semicolons, and operators. Core array methods are described like .push(), .pop(), and .shift(). Conditionals and comparison operators are also summarized.

Uploaded by

amandajbatts
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Free Coding Camp

JavaScript Algorithms and Data Structures: (Basic JavaScript 101)


July 1, 2023

- //comment = how to leave a comment on a code (unread by code; just for humans)
- 8 dif data types in JavaScript
- Undefined
- Null
- Boolean (T/F)
- Never written w/ “”
- String: “String literal” or ‘string’; computers cannot perform math on these
- Immutable once created
- Symbol
- Bigint
- Number
- Object (array)
- Variables: allow computers to store/manipulate data in a dynamic fashion
- Names can include numbers, letters, $, _ (no spaces)
- If unassigned, then considered “undefined” (**so if you do math on it, it will
come back as NaN “Not a Number”**)
- To declare= to create (a variable) for the 1st time by putting a keyword like var in
front
- If no keyword is used when inside a function, still considered global
- Function
- If no return statement, then value returned is considered “undefined”
- Act as placeholders of data they output
- consol.log( ) //runs the function inside the ( )
- To call a function = invoking a function
function reusableFunction() {
console.log("Hi World"); //this assigns function
}
reusableFunction(); //this calls the function
- //this divides the code to make the function reusable
- ; = used to end statements
- = = assignment operator
- “Initialize” = to initially (for the first time) assign value to variable
- Var a = 7 //this declares and initializes the variable all in one line of code
- Concatenate = to chain
- Case sensitivity= capitalization matters!
- MYVAR !== myVar
- Variables are written in camelCase
- Variable keywords:
- var: anything can be a variable (can be overwritten
intentionally/unintentionally)
- let (variables w/ same name can only be declared once)
let camper = Amy
let camper = Mike
//the above code will throw an error
//this avoids accidental overwrites
//can be seen only w/in scope of function or statement in which it is
declared
- const: follows rules of “let” & values cannot be different
const FAV_PET = cat
FAVE_PET = dog
//the above code will throw an error
-
- + addition symbol in JavaScript
- Also the concatenator symbol when used between 2 or more strings
- “My name is “ + myName + “ I concatenate.”
- - subtraction symbol
- * multiplication symbol
- / division symbol
- ++ increment symbol (it adds +1 to the symbol w/out need for = symbol)
- – decrement symbol (it adds -1 to the symbol) (i.e. i–)
- Decimals (i.e. 5.7) they may be rounded from actual answer
- % remainder symbol; gives remainder of the division of 2 numbers
- 5%2=1
- += plus equal operator //mean addition and assignment in one
- a += 5; // a + 5 =
- myStr += “ second sentence.”
- var ourStr = “Amanda is ”;
- var ourAdjective = “awesome!”;
- ourStr += ourAdjective //”Amanda is awesome!”
- -= minus equal operator //means subtract from variable
- a -= 5; // a - 5 =
- myVar = myVar - 5 //gives the command to subtract 5 from myVar
- myVar -= 5 //this is the same code as above, but shortened
- *= multiply equal operator //means multiply variable
- myVar = myVar * 5 //means multiply myVar 5X
- myVar *=5 //means the same thing
- /= divide equal operator //means divide variable
- myVar = myVar / 5 //means divide myVar by 5
- myVar /= 5 //means the same thing
- Escape sequences in string = use characters that aren’t counted in the code inside string
- \’ or \’ means the code will not count that quotation mark (use this for
example when you have a Shakespeare quote inside of a string)
- var sampleText = “And Shakespeare said \”no\””
- Or var sampleText = ‘And Shakespeare said “no”’
- \\ backslash
- \n = newline
- \t = tab
- \r = carriage return
- \b = backspace
- \f = form feed
- :\”<a> tag ???
- To append = to attach something
- .length //finds # of characters in a string or array
- var name = “Alan Peter”;
- name.length; //10 characters (bc spacebar)
- [ ] bracket notation finds character at specific index inside a string
- const firstName = “Amanda”;
- const firstLetter = firstName[0] //= “A”
- const secondLetterFirstName =firstName[1] // = “m”
- const lastLetter = firstName[firstName.length-1]; // = “a”
- Const thirdtoLastLetter = firstName[firstName.length-3]; // = “n”
- Array = arr= type of variable to store multiple pieces of data
- [ “dog”, “cat”, 5, “highway”]
- Const sandwich = [“peanut butter”, “jelly”, “bread”]
- Nesting arrays (AKA multidimensional arrays)
- Const teams = [[“bulls”, 23], [“white sox”, 31]]
- Array index
- to access array
const myArray = [50, 60, 70];
var myData = myArray[0]; //myData = 50
- To modify an array
const ourArray = [50, 40, 30];
ourArray[0] = 15; //ourArray = [15, 40, 30]
- To access nesting arrays
const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[[10, 11, 12], 13, 14]
];

const subarray = arr[3]; //=[[10,11,12],13,14]


const nestedSubarray = arr[3][0]; //=[10,11,12]
const element = arr[3][0][1]; // = 11
- To access nesting arrays
const ourPets = [
{
animalType: "cat",
names: [
"Meowzer",
"Fluffy",
"Kit-Cat"
]
},
{
animalType: "dog",
names: [
"Spot",
"Bowser",
"Frankie"
]
}
];

ourPets[0].names[1]; //= Fluffy


ourPets[1].names[0]; //= Spot

-
- .push() function = pushes (adds) data onto end of array
const arr1 = [1, 2, 3];
arr1.push(4); // arr1 = [1,2,3,4]
- .pop() function = removes last element from array, and returns the
removed element
const arr1 = [1, 2, 3];
arr1.pop(); // arr1 = [1,2] and return=3
- .shift() function = removes first element from array
- .unshift() function = adds element to front of array
- Shopping list= const myList = [[“chocolate”, 12], [“apples”, 3], [“water”, 1]]
- Parameters = placeholder variables for a function (typically written when defining a
function)
function functionWithArgs(param1, param2) {
console.log(param1+param2); //defines function
}
functionWithArgs(1,2); //calls the function; = 3
- Arguments = the imputed values to replace parameters in a function
- To pass = to input
- Return statement = command to send value back out of a function
function plusThree(num) {
return num + 3;
- Scope = visibility of variables
- Is the variable declared inside or outside of a function?
- What keyword is assigned?
- Local takes precedence over global scope
- Queue = abstract data structure where items are kept in an order
- Concerns .push, .pop, .shift, .unshift commands
- If statements = used to make decisions
- tells JavaScript to execute the code in the curly braces under certain conditions,
defined in the parentheses.
- Boolean condition
- Only executes code when true condition
if (condition is true) {
statement is executed
}
- Can have nested if statements
- Javascript knows these commands/words
- true = value for boolean statements
- false = value for boolean statements
- answer
- return
- undefined = mostly interchangeable with “null”
- val = value
- result = answer/result/return of function
- “” = empty string
- Arr = array
- n = nth location
- null = mostly interchangeable with “undefined”
-
- Operators:
- Comparison operators (boolean)
- == is equality operator (*dif than assignment operator =)
- Converts both values being compared to a common type // ‘8’ == 8
- === is same as == except does not perform type conversion // ‘8’ !===8
- != is the inequality operator
- Yes, converts values to common type
- !== is strict inequality operator
- No, doesn’t convert values to common type
- > is the greater than operator (yes converts dif values to common type)
- >= is greater than or equal to operator (yes converts dif data to common type)
- < is the less than operator (yes converts dif values to common type)
- type of operator = typeof 3 // = number
- typeof “3” // = string
- && is the logical and operator
- Statements (operands) to the left and right are BOTH true, returns true
- || is the logical or operator
- Returns true if either of operands are true
________________________
- Else statement = executed when condition of if statement is false
- Else if statements = when you have many conditions, then chain if statements together
- Order matters (first true operand will execute)
- Switch statement = compares values to case statements, will run until break; used inside
a function ; can replace if else statements to make it cleaner
- Uses strict equality (===)
switch(val) {
case 1:
return "one";
break;
case 2:
return "two";
Break;
case 3:
case 4:
case 5:
return "three-five";
break;
default:
return "other";
break;
}
- Default option in switch statement
- Like an “everything else” option; or like final “else” statement in if else
- Objects- (similar to arrays, but accessed differently; also flexible bc can store arrays, #,
strings, booleans, functions, etc)
const cat = { //object=cat
"name": "Whiskers", // property/key = name; legs, etc
"legs": 4, //value = 4
tails: 1,
"enemies": ["Water", "Dogs"]
};
- myObj.prop1; //gives you the first property of myObj; called dot notation
- myObj[“prop1”]; // gives you first property of myObj; called bracket notation
- Can use for outside variables as well
- Updating objects:
- cat.name = “Mr. Whiskers”; //now “name” = “Mr. Whiskers”
- Add new properties:
- cat.meow = “mee-yaowwwwwooo” //now “meow” = “mee-yaowwwwwooo”
- Delete properties:
- delete cat.meow; //now cat only has original 4 properties
- cat[val] //this gives me the values column of the object ‘cat’
- .hasOwnProperties(prop) = check if object’s property exists or not
- Boolean
const ourMusic = [ //ourMusic = object or complex data structure
{
"artist": "Daft Punk", //inside object is metadata
"title": "Homework", //key = “title”
"release_year": 1997, // value = 1997
"formats": [
"CD",
"Cassette",
"LP"
],
"gold": true
}
];
LOOPS
- While loops = runs code while specific condition is true, then stops
const ourArray = [];
let i = 0;

while (i < 5) {
ourArray.push(i);
i++;
} //while loop executes 5 times, appends numbers 0-4 to the array

- for loop = loop that runs a specific # of times


- For (a; b; c) // a=initializing statement; b=conditional statement; c=final
expression
const ourArray = [];

for (let i = 10; i > 0; i -= 2) {


ourArray.push(i);
} //ourArray = [10, 8, 6, 4, 2]
- Do…while loop =
- Replacing loops with recursion
function multiply(arr, n) {
let product = 1;
for (let i = 0; i < n; i++) {
product *= arr[i];
}
return product;
}

//rewritten as follows using recursion


function multiply(arr, n) {
if (n <= 0) {
return 1;
} else {
return multiply(arr, n - 1) * arr[n - 1];
}
}

- Math.random() function = random decimal # generator between 0-1 //not including 1


- Math.floor(Math.random() * (max - min + 1)) + min
- Random whole # generator between a given min and max
- Math.apply() =
- var arr = [6, 89, 3, 45];
- var maximus = Math.max.apply(null, arr); // maximus= 89
- parseInt function = converts string into integer
- const a = parseInt(str); // inputs string “007”, returns 7
- //if the first character in the ( ) isn’t a #, it will return NaN
- parseInt function w/ radix:
- parseInt(string, radix);
- const a = parseInt("11", 2); //returns 3 (bc returns base 10
answer)
- Conditional operator (AKA ternary operator) = one line if/else statement
- function findGreater(a, b) {
- return a > b ? "a is greater" : "b is greater or equal";
- V
- function checkSign(num) {
- return (num > 0) ? "positive"
- : (num === 0) ? "zero"
- : "negative";
- }
- Use recursion to create countdown/up:
- function countup(n) {
- if (n < 1) {
- return [];
- } else {
- const countArray = countup(n - 1);
- countArray.push(n);
- return countArray;
- }
- }
- console.log(countup(5)); //=[1, 2, 3, 4, 5]

ES6
- Object.freeze = makes obj immutable
- let obj = {
- name:"FreeCodeCamp",
- review:"Awesome"
- };
- Object.freeze(obj); //makes obj immutable; (capitalized “O”)
- obj.review = "bad"; //will return error
- obj.newProp = "Test"; //will return error
- console.log(obj); // ={ name: "FreeCodeCamp", review:
"Awesome" }
-
- What is “strict mode”?
- Arrow function syntax:
- const myFunc = function() {
- const myVar = "value";
- return myVar;
- }
- //rewritten as follows:
- const myFunc = () => {
- const myVar = "value";
- return myVar;
- }
- //rewritten as follows:
- const myFunc = () => "value";
- .concat() =
- const str1 = 'Hello';
- const str2 = str1.concat(' ', 'World');
- Arrow functions with parameters
- const doubler = (item) => item * 2;
- doubler(4); // =8
-
- const greeting = (name = "Anonymous") => "Hello " + name;
-
- console.log(greeting("John")); // = “Hello John”
- console.log(greeting()); // = “Hello Anonymous”
-
- Rest parameters:
- function howMany(...args) {
- return "You have passed " + args.length + " arguments.";
- }
- console.log(howMany(0, 1, 2)); //= “You have passed 3 arguments.”
- console.log(howMany("string", null, [1, 2, 3], { })); //= “You
have passed 4 arguments.”
- Spread operator =

You might also like