JS Fundamentals
Thu Jun 27 2024 22:26:09 GMT+0000 (Coordinated Universal Time)
Saved by @NoFox420 #javascript
Now you can start writing your JavaScript. Begin by creating a script element. This element is used to load JavaScript into your HTML file. <script> // JavaScript code goes here </script> One of the most powerful tools is your developer console. Depending on your browser, this might be opened by pressing F12 or Ctrl+Shift+I. On Mac, you can press Option + ⌘ + C and select "Console". You can also click the "Console" button above the preview window to see our built-in console. The developer console will include errors that are produced by your code, but you can also use it to see values of variables in your code, which is helpful for debugging. JavaScript interacts with the HTML using the Document Object Model, or DOM. The DOM is a tree of objects that represents the HTML. You can access the HTML using the document object, which represents your entire HTML document. One method for finding specific elements in your HTML is using the querySelector() method. The querySelector() method takes a CSS selector as an argument and returns the first element that matches that selector. For example, to find the <h1> element in your HTML, you would write: let h1 = document.querySelector("h1"); Note that h1 is a string and matches the CSS selector you would use. We have run into a slight problem. You are trying to query your page for a button element, but your script tag is in the head of your HTML. This means your code runs before the browser has finished reading the HTML, and your document.querySelector() will not see the button - because the browser hasn't processed it yet. To fix this, move your script element out of the head element, and place it at the end of your body element (just before the closing <body> tag.) button1 represents your first button element. These elements have a special property called onclick, which you can use to determine what happens when someone clicks that button. You can access properties in JavaScript a couple of different ways. The first is with dot notation. Here is an example of using dot notation to set the onclick property of a button to a function reference. button.onclick = myFunction; In this example, button is the button element, and myFunction is a reference to a function. When the button is clicked, myFunction will be called. The innerText property controls the text that appears in an HTML element. For example: <p id="info">Demo content</p> Example Code const info = document.querySelector("#info"); info.innerText = "Hello World"; The following example would change the text of the p element from Demo content to Hello World. Objects are an important data type in JavaScript. The next few steps will be dedicated to learning about them so you will better understand how to apply them in your project. Objects are non primitive data types that store key-value pairs. Non primitive data types are mutable data types that are not undefined, null, boolean, number, string, or symbol. Mutable means that the data can be changed after it is created. Here is the basic syntax for an object: { key: value } Objects are similar to arrays, except that instead of using indexes to access and modify their data, you access the data in objects through properties. Properties consist of a key and a value. The key is the name of the property, and the value is the data stored in the property. Here is an example of an object with a single property: const obj = { name: "Quincy Larson" }; If the property name (key) of an object has a space in it, you will need to use single or double quotes around the name. Here is an example of an object with a property name that has a space: const spaceObj = { "Space Name": "Kirk", }; If you tried to write a key without the quotes, it would throw an error: const spaceObj = { // Throws an error Space Name: "Kirk", }; There are two ways to access the properties of an object: dot notation (.) and bracket notation ([]), similar to an array. Dot notation is what you use when you know the name of the property you're trying to access ahead of time. object.property; Here is a sample of using dot notation (.) to read the name property of the developer object: const developer = { name: "Jessica", } // Output: Jessica console.log(developer.name); The second way to access the properties of an object is bracket notation ([]). If the property of the object you are trying to access has a space in its name, you will need to use bracket notation. objectName["property name"]; Here is a sample of using bracket notation to read an object's property: const spaceObj = { "Space Name": "Kirk", }; spaceObj["Space Name"]; // "Kirk" By default, the HTML element that shows the monster's stats has been hidden with CSS. When the player clicks the "Fight dragon" button, the monster's stats should be displayed. You can accomplish this by using the style and display properties on the monsterStats element. The style property is used to access the inline style of an element and the display property is used to set the visibility of an element. Here is an example of how to update the display for a paragraph element: const paragraph = document.querySelector('p'); paragraph.style.display = 'block'; The Math object in JavaScript contains static properties and methods for mathematical constants and functions. One of those is Math.random(), which generates a random number from 0 (inclusive) to 1 (exclusive). Another is Math.floor(), which rounds a given number down to the nearest integer. Using these, you can generate a random number within a range. For example, this generates a random number between 1 and 5: Math.floor(Math.random() * 5) + 1;. The innerHTML property allows you to access or modify the content inside an HTML element using JavaScript. Here is an example of updating the content for this paragraph element using the innerHTML property. <p id="demo">This is a paragraph.</p> document.querySelector("#demo").innerHTML = "Hello, innerHTML!"; The ternary operator is a conditional operator and can be used as a one-line if-else statement. The syntax is: condition ? expressionIfTrue : expressionIfFalse. Here is an example of returning a value using an if-else statement and a refactored example using a ternary operator: // if-else statement if (score > 0) { return score } else { return default_score } // ternary operator return score > 0 ? score : default_score The logical OR operator will use the first value if it is truthy – that is, anything apart from NaN, null, undefined, 0, -0, 0n, "", and false. Otherwise, it will use the second value. For example: num < 10 || num > 20. The .includes() method determines if an array contains an element and will return either true or false. Here is an example of the .includes() syntax: Example Code const numbersArray = [1, 2, 3, 4, 5] const number = 3 if (numbersArray.includes(number)) { console.log("The number is in the array.") }
Comments