HTML, Css Java
HTML, Css Java
<h1>…………</h2>
H3,h4,h5,h6
<p>………….</p>
Commenting <!--……..-->
<main> <p>……..</p>
<p>…….</p>
</main>
target is an anchor tag attribute that specifies where to open the link. The value _blank specifies to open
the link in a new tab. The href is an anchor tag attribute that contains the URL address of the link:
<p>
</p>
Unordered lists start with an opening <ul> element, followed by any number of <li> elements. Finally,
unordered lists close with a </ul>.
<ul>
<li>cat nip</li>
<li>laser pointers</li>
<li>lasagna</li>
</ul>
Ordered lists start with an opening <ol> element, followed by any number of <li> elements. Finally,
ordered lists are closed with the </ol> tag.
input elements are a convenient way to get input from your user.
<input type="text">
Placeholder text is what is displayed in your input element before your user has inputted anything.
You can build web forms that actually submit data to a server using nothing more than pure HTML. You
can do this by specifying an action attribute on your form element.
<form action="url-where-you-want-to-submit-form-data">
<input>
</form>
a submit button to your form. Clicking this button will send the data from your form to the URL you
specified with your form's action attribute
<button type="submit">submit</button>
if you wanted to make a text input field required, you can just add the attribute required within your
input element, like this: <input type="text" required>
You can use radio buttons for questions where you want the user to only give you one answer out of
multiple options.
Radio buttons are a type of input.
Each of your radio buttons can be nested within its own label element. By wrapping an input element
inside of a label element it will automatically associate the radio button input with the label element
surrounding it.
All related radio buttons should have the same name attribute to create a radio button group. By
creating a radio group, selecting any single radio button will automatically deselect the other buttons
within the same group ensuring only one answer is provided by the user.
<label>
<input type="radio" name="indoor-outdoor">Indoor
</label>
It is considered best practice to set a for attribute on the label element, with a value that matches the
value of the id attribute of the input element. This allows assistive technologies to create a linked
relationship between the label and the related input element.
<label for="indoor">
<input id="indoor" type="radio" name="indoor-outdoor">Indoor
</label>
Example code full:
<label>
<input type="radio" name="indoor-outdoor">Indoor
<input id="indoor" type="radio" name="indoor-
outdoor">Indoor
<label for="indoor">Indoor</label>
<label for="indoor">
<input id="indoor" type="radio" name="indoor-
outdoor">indoor
</label>
</label>
<label>
<input type="radio" name="indoor-outdoor">Outdoor
<input id="outdoor" type="radio" name="indoor-
outdoor">Outdoor
<label for="outdoor">Outdoor</label>
<label for="outdoor">
<input id="outdoor" type="radio" name="indoor-
outdoor">outdoor
</label>
</label>
Each of your checkboxes can be nested within its own label element. By wrapping an input element
inside of a label element it will automatically associate the checkbox input with the label element
surrounding it.
All related checkbox inputs should have the same name attribute.
It is considered best practice to explicitly define the relationship between a checkbox input and its
corresponding label by setting the for attribute on the label element to match the id attribute of the
associated input element.
<label>
<label for="loving"><input id="loving" type="checkb
ox" name="personality">loving</label>
</label>
<label>
<label for="caring"><input id="caring" type="checkb
ox" name="personality">caring</label>
</label>
<label>
<label for="sweet"><input id="sweet" type="checkbox
" name="personality">sweet</label>
</label>
When a form gets submitted, the data is sent to the server and includes entries for the options selected.
Inputs of type radio and checkbox report their values from the value attribute.
<label for="indoor">
<input id="indoor" value="indoor" type="radio" name="indoor-
outdoor">Indoor
</label>
<label for="outdoor">
<input id="outdoor" value="outdoor" type="radio"
name="indoor-outdoor">Outdoor
</label>
Here, you have two radio inputs. When the user submits the form with the indoor option selected, the
form data will include the line: indoor-outdoor=indoor. This is from the name and value attributes of the
"indoor" input.
If you omit the value attribute, the submitted form data uses the default value, which is on. In this
scenario, if the user clicked the "indoor" option and submitted the form, the resulting form data would
be indoor-outdoor=on, which is not useful. So the value attribute needs to be set to something to
identify the option.
You can set a checkbox or radio button to be checked by default using the checked attribute.
To do this, just add the word checked to the inside of an input element.
The div element, also known as a division element, is a general purpose container for other elements.
The div element is probably the most commonly used HTML element of all.
Just like any other non-self-closing element, you can open a div element with <div> and close it on
another line with </div>.
At the top of your document, you need to tell the browser which version of HTML your page is using.
HTML is an evolving language, and is updated regularly. Most major browsers support the latest
specification, which is HTML5. However, older web pages may use previous versions of the language.
You tell the browser this information by adding the <!DOCTYPE ...> tag on the first line, where the ... part
is the version of HTML. For HTML5, you use <!DOCTYPE html>.
The ! and uppercase DOCTYPE is important, especially for older browsers. The html is not case sensitive.
Next, the rest of your HTML code needs to be wrapped in html tags. The opening <html> goes directly
below the <!DOCTYPE html> line, and the closing </html> goes at the end of the page.
<!DOCTYPE html>
<html>
</html>
You can add another level of organization in your HTML document within the html tags with the head
and body elements. Any markup with information about your page would go into the head tag. Then any
markup with the content of the page (what displays for a user) would go into the body tag.
Metadata elements, such as link, meta, title, and style, typically go inside the head element.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example title</title>
</head>
<body>
<div>
</div>
</body>
</html>
CSS
We can do this by changing the style of your h2 element.
The property that is responsible for the color of an element's text is the color style property.
h1 {
font-size: 30px;
}
<style>
.red-text {
color: red;
p{font-size: 16px;}
}
</style>
You can set which font an element should use, by using the
font-family property.
h2 {
font-family: sans-serif;
}
To import a Google Font, you can copy the font's URL from the Google Fonts library and then paste it in
your HTML. For this challenge, we'll import the Lobster font. To do this, copy the following code snippet
and paste it into the top of your code editor (before the opening style element):
<link href="https://fonts.googleapis.com/css?family=Lobster"
rel="stylesheet" type="text/css">
Now you can use the Lobster font in your CSS by using Lobster as the FAMILY_NAME
Family names are case-sensitive and need to be wrapped in quotes if there is a space in the name. For
example, you need quotes to use the "Open Sans" font, but not to use the Lobster font.
CSS has a property called width that controls an element's width. Just like with fonts, we'll use px (pixels)
to specify the image's width.
For example, if we wanted to create a CSS class called larger-image that gave HTML elements a width of
500 pixels, we'd use:
<style>
.larger-image {
width: 500px;
}
</style>
Full code example
<style>
.thin-red-border {
border-color: red;
border-width: 5px;
border-style: solid;
}
</style>
you can apply multiple classes to an element using its class attribute, by separating each class name with
a space. For example:
Your cat photo currently has sharp corners. We can round out those corners with a CSS property called
border-radius.
In addition to pixels, you can also specify the border-radius using a percentage.
You can set an element's background color with the background-color property.
.green-background {
background-color: green;
}
There are several benefits to using id attributes: You can use an id to style a single element and later
you'll learn that you can use them to select and modify specific elements with JavaScript.
id attributes should be unique. Browsers won't enforce this, but it is a widely agreed upon best practice.
So please don't give more than one element the same id attribute.
<h2 id="cat-photo-app">
One cool thing about id attributes is that, like classes, you can style them using CSS.
#cat-photo-element {
background-color: green;
}
You always reference ids by putting a # in front of their names.
Three important properties control the space that surrounds each HTML element: padding, border, and
margin.
An element's padding controls the amount of space between the element's content and its border.
Here, we can see that the blue box and the red box are nested within the yellow box. Note that the red
box has more padding than the blue box.
When you increase the blue box's padding, it will increase the distance (padding) between the text and
the border around it.
An element's margin controls the amount of space between an element's border and surrounding
elements.
Here, we can see that the blue box and the red box are nested within the yellow box. Note that the red
box has a bigger margin than the blue box, making it appear smaller.
If you set an element's margin to a negative value, the element will grow larger.
Sometimes you will want to customize an element so that it has different amounts of padding on each of
its sides.
CSS allows you to control the padding of all four individual sides of an element with the padding-top,
padding-right, padding-bottom, and padding-left properties.
CSS allows you to control the margin of all four individual sides of an element with the margin-top,
margin-right, margin-bottom, and margin-left properties.
four values work like a clock: top, right, bottom, left, and will produce the exact same result as using the
side-specific padding instructions.
These are known as ID and class selectors. There are other CSS Selectors you can use to select custom
groups of elements to style. The [attr=value] selector matches and styles elements with a specific
attribute value. For example, the below code changes the margins of all elements with the attribute type
and a corresponding value of radio:
[type='radio'] {
margin: 20px 0px 20px 0px;
}
The two main types of length units in CSS are absolute and relative. Absolute units tie to physical units of
length. For example, in and mm refer to inches and millimeters, respectively. Absolute length units
approximate the actual measurement on a screen, but there are some differences depending on a
screen's resolution.
Relative units, such as em or rem, are relative to another length value. For example, em is based on the
size of an element's font. If you use it to set the font-size property itself, it's relative to the parent's font-
size.
Every HTML page has a body element. We can prove that the body element exists here by giving it a
background-color of black.
body {
background-color: black;
}
ou can style your body element just like any other HTML element, and all your other elements will
inherit your body element's styles.
Complete example code
<h1>Hello World</h1>
<style>
body {
background-color: black;
color: green;
font-family: monospace;
}
</style>
what happens when we create a class that makes text pink, then apply it to an element. Our class
override the body element's color: green
class="class1 class2"
the order of the class declarations in the <style> section is what is
important. The second declaration will always take precedence over the first.
Because .blue-text is declared second, it overrides the attributes of .pink-
text. An id can override class. An inline style, <h1 style="color:
green;"> overrides id.
We can use !imporatant to avoid the overriding.
Another way you can represent colors in CSS is by using RGB values.
The RGB value for black looks like this:
rgb(0, 0, 0)
The RGB value for white looks like this:
rgb(255, 255, 255)
If you do the math, the two digits for one color equal 16 times 16, which
gives us 256 total values. So RGB, which starts counting from zero, has the
exact same number of possible values as hex code. you specify the brightness
of each color with a number between 0 and 255.
CSS Variables are a powerful way to change many CSS style properties at once
by changing only one value.
.penguin {
--penguin-skin: black;
--penguin-belly: gray;
--penguin-beak: yellow;
}
To create a CSS variable, you just need to give it a name with two hyphens in
front of it and assign it a value like this:
--penguin-skin: gray;
The following will change the background of whatever element
you are targeting to gray because that is the value of the --
penguin-skin variable.
When using your variable as a CSS property value, you can
attach a fallback value that your browser will revert to if the
given variable is invalid.
background: var(--penguin-skin, black);
When working with CSS you will likely run into browser compatibility issues at
some point. This is why it's important to provide browser fallbacks to avoid
potential problems.
When your browser parses the CSS of a webpage, it ignores any properties that
it doesn't recognize or support. For example, if you use a CSS variable to
assign a background color on a site, Internet Explorer will ignore the
background color because it does not support CSS variables. In that case, the
browser will use whatever value it has for that property. If it can't find any
other value set for that property, it will revert to the default value, which
is typically not ideal.
This means that if you do want to provide a browser fallback, it's as easy as
providing another more widely supported value immediately before your
declaration. That way an older browser will have something to fall back on,
while a newer browser will just interpret whatever declaration comes later in
the cascade.
<style>
:root {
--red-color: red;
}
.red-box {
background: red;
background: var(--red-color);
height: 200px;
width:200px;
}
</style>
<div class="red-box"></div>
:root {
--penguin-size: 300px;
--penguin-skin: gray;
--penguin-belly: white;
--penguin-beak: orange;
}
--penguin-skin: black;
--penguin-size: 200px;
JAVA
Comments are lines of code that JavaScript will intentionally ignore. Comments
are a great way to leave notes to yourself and to other people who will later
need to figure out what that code does.
var ourName;
creates a variable called ourName. In JavaScript we end statements with
semicolons. Variable names can be made up of numbers, letters, and $ or _, but
may not contain spaces or start with a number.
var myVar;
myVar = 5;
After a value is assigned to a variable using the assignment operator, you can
assign the value of that variable to another variable using the assignment
operator.
var myVar;
myVar = 5;
var myNum;
myNum = myVar;
It is common to initialize a variable to an initial value in the same line as
it is declared.
var myVar = 0;
you can also declare a string variable like this:
In JavaScript all variables and function names are case sensitive. This means
that capitalization matters.
Write variable names in JavaScript in camelCase. In camelCase, multi-word
variable names have the first word in lowercase and the first letter of each
subsequent word is capitalized.
var someVariable;
var anotherVariableName;
var thisVariableNameIsSoLong;
One of the biggest problems with declaring variables with the var keyword is
that you can easily overwrite variable declarations:
const myVar = 12 - 6;
We can also multiply one number by another.
i++;
is equivalent to
i = i + 1;
similarly we can decrement a variable
i--;
We can store decimal numbers in variables too. Decimal numbers are sometimes
referred to as floating point numbers or floats.
In JavaScript, you can also perform calculations with decimal numbers, just
like whole numbers.
The remainder operator % gives the remainder of the division of two numbers.
myVar = myVar + 5;
to add 5 to myVar. Since this is such a common pattern, there are operators
which do both a mathematical operation and assignment in one step. One such
operator is the += operator.
When you are defining a string you must start and end with a single or double
quoteWhen you are defining a string you must start and end with a single or
double quote
When you are defining a string you must start and end with a single or double
quote
In the goodStr above, you can use both quotes safely by using the backslash \
as an escape character.
Quotes are not the only characters that can be escaped inside a string. Escape
sequences allow you to use characters you may not otherwise be able to use in
a string.
We can also use the += operator to concatenate a string onto the end of an
existing string variable. This can be very helpful to break a long string over
several lines.
Sometimes you will need to build a string. By using the concatenation operator
(+), you can insert one or more variables into a string you're building.
console.log("Alan Peter".length);
lastNameLength = lastName.length;
Bracket notation is a way to get a character at a specific index within a
string.
Array indexes are written in the same bracket notation that strings use,
except that instead of specifying a character, they are specifying an entry in
the array. Like strings, arrays use zero-based indexing, so the first element
in an array has an index of 0.
pop() always removes the last element of an array. What if you want to remove
the first?
That's where .shift() comes in. It works just like .pop(), except it removes
the first element instead of the last.
Not only can you shift elements off of the beginning of an array, you can also
unshift elements to the beginning of an array i.e. add elements in front of
the array.
function functionName() {
console.log("Hello World");
}
Parameters are variables that act as placeholders for the values that are to
be input to a function when it is called. When a function is defined, it is
typically defined along with one or more parameters. The actual values that
are input (or "passed") into a function when it is called are known as
arguments.
function plusThree(num) {
return num + 3;
}
let sum = 0;
function addSum(num) {
sum = sum + num;
}
addSum(3);
If you'll recall from our discussion about Storing Values with the Assignment
Operator, everything to the right of the equal sign is resolved before the
value is assigned. This means we can take the return value of a function and
assign it to a variable.
In Computer Science a queue is an abstract Data Structure where items are kept
in order. New items can be added at the back of the queue and old items are
taken off from the front of the queue.
Another data type is the Boolean. Booleans may only be one of two values: true
or false. They are basically little on-off switches, where true is on and
false is off. These two states are mutually exclusive.
if (condition is true) {
statement is executed
The most basic operator is the equality operator ==. The equality operator
compares two values and returns true if they're equivalent or false if they
are not. Note that equality is different from assignment (=), which assigns
the value on the right of the operator to a variable on the left.
function equalityTest(myVal) {
if (myVal == 10) {
return "Equal";
}
return "Not Equal";
}
Full code
function testEqual(val) {
if (val==12) { // Change this line
return "Equal";
}
return "Not Equal";
}
testEqual(10);
Strict equality (===) is the counterpart to the equality operator (==).
However, unlike the equality operator, which attempts to convert both values
being compared to a common type, the strict equality operator does not perform
a type conversion.
3 === 3 // true
3 === '3' // false
In JavaScript, you can determine the type of a variable or a value with the
typeof operator, as follows:
typeof 3
typeof '3'
The inequality operator (!=) is the opposite of the equality operator. It
means not equal and returns false where equality would return true and vice
versa. Like the equality operator, the inequality operator will convert data
types of values while comparing.
1 != 2 // true
1 != "1" // false
1 != '1' // false
1 != true // false
0 != false // false
The strict inequality operator (!==) is the logical opposite of the strict
equality operator. It means "Strictly Not Equal" and returns false where
strict equality would return true and vice versa. The strict inequality
operator will not convert data types.
3 !== 3 // false
3 !== '3' // true
4 !== 3 // true
The greater than operator (>) compares the values of two numbers. If the
number to the left is greater than the number to the right, it returns true.
Otherwise, it returns false.
The greater than or equal to operator (>=) compares the values of two numbers.
If the number to the left is greater than or equal to the number to the right,
it returns true. Otherwise, it returns false.
The less than operator (<) compares the values of two numbers. If the number
to the left is less than the number to the right, it returns true. Otherwise,
it returns false. Like the equality operator, the less than operator converts
data types while comparing.
The less than or equal to operator (<=) compares the values of two numbers. If
the number to the left is less than or equal to the number to the right, it
returns true. If the number on the left is greater than the number on the
right, it returns false. Like the equality operator, the less than or equal to
operator converts data types.
Sometimes you will need to test more than one thing at a time. The logical and
operator (&&) returns true if and only if the operands to the left and right
of it are true.
The logical or operator (||) returns true if either of the operands is true.
Otherwise, it returns false.
if (condition1) {
statement1
} else if (condition2) {
statement2
} else if (condition3) {
statement3
. . .
} else {
statementN
}
If you need to match one value against many options, you can use a switch
statement. A switch statement compares the value to the case statements which
define various possible values. Any valid JavaScript statements can be
executed inside a case block and will run from the first matched case value
until a break is encountered.
switch (fruit) {
case "apple":
console.log("The fruit is an apple");
break;
case "orange":
console.log("The fruit is an orange");
break;
}
In a switch statement you may not be able to specify all possible values as
case statements. Instead, you can add the default statement which will be
executed if no matching case statements are found. Think of it like the final
else statement in an if/else chain.
switch (num) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
default:
defaultStatement;
break;
}
If the break statement is omitted from a switch statement's case, the
following case statement(s) are executed until a break is encountered. If you
have multiple inputs with the same output, you can represent them in a switch
statement like this:
let result = "";
switch (val) {
case 1:
case 2:
case 3:
result = "1, 2, or 3";
break;
case 4:
result = "4 alone";
}
If you have many options to choose from, a switch statement can be easier to
write than many chained if/else if statements. The following:
You may recall from Comparison with the Equality Operator that all comparison
operators return a boolean true or false value.
Sometimes people use an if/else statement to do a comparison, like this:
function isEqual(a, b) {
if (a === b) {
return true;
} else {
return false;
}
}
But there's a better way to do this. Since === returns true or false, we can
return the result of the comparison:
function isEqual(a, b) {
return a === b;
}
When a return statement is reached, the execution of the current function
stops and control returns to the calling location.
function myFun() {
console.log("Hello");
return "World";
console.log("byebye")
}
myFun();
The above will display the string Hello in the console, and return the string
World. The string byebye will never display in the console, because the
function exits at the return statement.
Objects are similar to arrays, except that instead of using indexes to access
and modify their data, you access the data in objects through what are called
properties.
const cat = {
"name": "Whiskers",
"legs": 4,
"tails": 1,
"enemies": ["Water", "Dogs"]
};
In this example, all the properties are stored as strings, such as name, legs,
and tails. However, you can also use numbers as properties. You can even omit
the quotes for single-word string properties, as follows:
const anotherObject = {
make: "Ford",
5: "five",
"model": "focus"
};
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.
const myObj = {
prop1: "val1",
prop2: "val2"
};
const myObj = {
"Space Name": "Kirk",
"More Space": "Spock",
"NoSpace": "USS Enterprise"
};
myObj["Space Name"];
myObj['More Space'];
myObj["NoSpace"];
myObj["Space Name"] would be the string Kirk, myObj['More Space'] would be the
string Spock, and myObj["NoSpace"] would be the string USS Enterprise.
const dogs = {
Fido: "Mutt",
Hunter: "Doberman",
Snoopie: "Beagle"
};
ourDog.bark = "bow-wow";
We can also delete properties from objects like this:
delete ourDog.bark;
Objects can be thought of as a key/value storage, like a dictionary. If you
have tabular data, you can use an object to lookup values rather than a switch
statement or an if/else chain. This is most useful when you know that your
input data is limited to a certain range.
Here is an example of an article object:
const article = {
"title": "How to create objects in JavaScript",
"link": "https://www.freecodecamp.org/news/a-complete-guide-
to-creating-objects-in-javascript-b0e2450655e8/",
"author": "Kaashan Hussain",
"language": "JavaScript",
"tags": "TECHNOLOGY",
"createdAt": "NOVEMBER 28, 2018"
};
const ourMusic = [
{
"artist": "Daft Punk",
"title": "Homework",
"release_year": 1997,
"formats": [
"CD",
"Cassette",
"LP"
],
"gold": true
}
];
n the example above, "artist": "Daft Punk" is a property that has a key of
artist and a value of Daft Punk.
As we have seen in earlier examples, objects can contain both nested objects
and nested arrays. Similar to accessing nested objects, array bracket notation
can be chained to access nested arrays.
const ourPets = [
{
animalType: "cat",
names: [
"Meowzer",
"Fluffy",
"Kit-Cat"
]
},
{
animalType: "dog",
names: [
"Spot",
"Bowser",
"Frankie"
]
}
];
ourPets[0].names[1];
ourPets[1].names[0];
ourPets[0].names[1] would be the string Fluffy, and ourPets[1].names[0] would
be the string Spot.
The first type of loop we will learn is called a while loop because it runs
while a specified condition is true and stops once that condition is no longer
true.
while (i < 5) {
ourArray.push(i);
i++;
}
In the code example above, the while loop will execute 5 times and append the
numbers 0 through 4 to ourArray.
We'll start at i = 0 and loop while i < 10. We'll increment i by 2 each loop
with i += 2.
A for loop can also count backwards, so long as we can define the right
conditions.
In order to decrement by two each iteration, we'll need to change our
initialization, condition, and final expression.
We'll start at i = 10 and loop while i > 0. We'll decrement i by 2 each loop
with i -= 2.
do {
ourArray.push(i);
i++;
} while (i < 5);
Ex
const ourArray = [];
let i = 5;
while (i < 5) {
ourArray.push(i);
i++;
}
Recursion is the concept that a function can be expressed in
terms of itself. To help understand this, start by thinking
about the following task: multiply the first n elements of an
array to create the product of those elements. Using a for
loop, you could do this:
function multiply(arr, n) {
let product = 1;
for (let i = 0; i < n; i++) {
product *= arr[i];
}
return product;
}
JavaScript has a Math.random() function that generates a random
decimal number between 0 (inclusive) and 1 (exclusive). Thus
Math.random() can return a 0 but never return a 1.
You can generate random decimal numbers with Math.random(), but
sometimes you need to generate random whole numbers. The
following process will give you a random whole number less than
20:
You'll call your minimum number min and your maximum number max.
This formula gives a random whole number in the range from min to max. Take a
moment to read it and try to understand what this code is doing:
parseInt(string, radix);
And here's an example:
The conditional operator, also called the ternary operator, can be used as a
one line if-else expression.
function findGreater(a, b) {
if(a > b) {
return "a is greater";
}
else {
return "b is greater or equal";
}
}
This can be re-written using the conditional operator:
function findGreater(a, b) {
return a > b ? "a is greater" : "b is greater or equal";
}
In the previous challenge, you used a single conditional operator. You can
also chain them together to check for multiple conditions.
The following function uses if, else if, and else statements to check multiple
conditions:
function findGreaterOrEqual(a, b) {
if (a === b) {
return "a and b are equal";
}
else if (a > b) {
return "a is greater";
}
else {
return "b is greater";
}
}
The above function can be re-written using multiple conditional operators:
function findGreaterOrEqual(a, b) {
return (a === b) ? "a and b are equal"
: (a > b) ? "a is greater"
: "b is greater";
}
The base case tells the recursive function when it no longer needs to call
itself. It is a simple case where the return value is already known. There
will also be a recursive call which executes the original function with
different arguments. If the function is written correctly, eventually the base
case will be reached.
For example, say you want to write a recursive function that returns an array
containing the numbers 1 through n. This function will need to accept an
argument, n, representing the final number. Then it will need to call itself
with progressively smaller values of n until it reaches 1. You could write the
function as follows:
function countup(n) {
if (n < 1) {
return [];
} else {
const countArray = countup(n - 1);
countArray.push(n);
return countArray;
}
}
console.log(countup(5));
The value [1, 2, 3, 4, 5] will be displayed in the console.
At first, this seems counterintuitive since the value of n decreases, but the
values in the final array are increasing. This happens because the push
happens last, after the recursive call has returned. At the point where n is
pushed into the array, countup(n - 1) has already been evaluated and returned
[1, 2, ..., n - 1].