string number boolean undefined
var constAnswer: var is used to create and initialize a variable whose value can be changed later:
var n = 384; n = 391;const is used to create a constant variable that cannot be changed later:
const PI = 3.14159265;
function makeGreeting(firstName) { var greeting = "Hello, " + fname + ", how are you?"; return greeting; } // Test the makeGreeting function: var greeting = makeGreeting("Alice"); var greeting = makeGreeting("Larry"); // Output: Hello, Alice, how are you? Hello, Larry, how are you?
frigid cold chilly perfect warm hotUse if..else statements to assign a descriptor to a temperature. Test your function. Answer:
function descriptor(temp) { if (temp < 25) { return "frigid"; } else if (temp < 50) { return "cold" } else if (temp < 65) { return "chilly"; } else if (temp < 75) { return "perfect"; } else if (temp < 95) { return "warm"; } else { return "hot"; } } console.log(descriptor(-7)); console.log(descriptor(43)); console.log(descriptor(62)); console.log(descriptor(71)); console.log(descriptor(89)); console.log(descriptor(102)); // Output: frigid cold chilly perfect warm hot
var arr = [67, 43, 90, 48, 71];
Index | Value |
---|---|
0 | 67 |
1 | 43 |
2 | 90 |
3 | 48 |
4 | 71 |
var arr = [67, 43, 90, 48, 71]; console.log(arr[3]); // Output: 48
var b = [5, 3, 2, 9, 4]; var i = 1; console.log(b[i + 1] + " " + b[i] + 1);Answer: This problem checks if you know the difference between adding one to the index before looking up the array value and adding one to the array value after looking it up.
b[i + 1] = b[1 + 1] = b[2] = 2 b[i] + 1 = b[1] + 1 = 3 + 1 = 4 The output: 2 4
var items = ["zero", "one", "two", "three", "four"];with equal probability 1/5. Answer:
var n = 5; var randomInt = Math.floor(Math.random( ) * n); console.log(items[randomInt]);
one two three four fivewith the probability 1/5. Test your function. Answer:
function chooseRandomNumber( ) { var items = ["zero", "one", "two", "three", "four"]; var n = 5; var randomInt = Math.floor(Math.random( ) * n); console.log(items[randomInt]); } console.log(chooseRandomNumber( ));You can replace the line
var n = 5;with
var n = items.length;so that the function works with an items array of any size.
var name = "Larry"; var amt = 524.67;Define the variable sentence like this:
var sentence = name + " owes me $" + amt;The resulting value of sentence is:
"Larry owes me $524.67."
var sentence = `${name} owes me $${amt}.`;
var x = 2, y = 2; console.log(`${x} + ${y} == ${x + y}`);