const myText = "I am a string";
const newString = myText.replace("string", "sausage");
console.log(newString);
// the replace() string function takes a source string,
// and a target string and replaces the source string,
// with the target string, and returns the newly formed stringFunctions — reusable blocks of code / notebook
Functions — reusable blocks of code
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
const myArray = ["I", "love", "chocolate", "frogs"];
const madeAString = myArray.join(" ");
console.log(madeAString);
// the join() function takes an array, joins
// all the array items together into a single
// string, and returns this new stringconst myNumber = Math.random();
// the random() function generates a random number between
// 0 and up to but not including 1, and returns that numberfunction draw() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
for (let i = 0; i < 100; i++) {
ctx.beginPath();
ctx.fillStyle = "rgb(255 0 0 / 50%)";
ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
ctx.fill();
}
}draw();function random(number) {
return Math.floor(Math.random() * number);
}function myFunction() {
alert("hello");
}
myFunction();
// calls the function onceconst myNumber = Math.random();const myText = "I am a string";
const newString = myText.replace("string", "sausage");const myArray = ["I", "love", "chocolate", "frogs"];
const madeAString = myArray.join(" ");
console.log(madeAString);
// returns 'I love chocolate frogs'
const madeAnotherString = myArray.join();
console.log(madeAnotherString);
// returns 'I,love,chocolate,frogs'function hello(name = "Chris") {
console.log(`Hello ${name}!`);
}
hello("Ari"); // Hello Ari!
hello(); // Hello Chris!function myFunction() {
alert("hello");
}(function () {
alert("hello");
});function logKey(event) {
console.log(`You pressed "${event.key}".`);
}
textBox.addEventListener("keydown", logKey);textBox.addEventListener("keydown", function (event) {
console.log(`You pressed "${event.key}".`);
});textBox.addEventListener("keydown", (event) => {
console.log(`You pressed "${event.key}".`);
});const doubled = originals.map(function (item) {
return item * 2;
});<input id="textBox" type="text" />
<div id="output"></div>const textBox = document.querySelector("#textBox");
const output = document.querySelector("#output");
textBox.addEventListener("keydown", (event) => {
output.textContent = `You pressed "${event.key}".`;
});