# Decision making in Js
- This concept is pretty universal.
- Having different outcomes based off of certain criteria.
- For example, on Reddit, You can get two different outcomes when you singed in or not. It's just having different branching paths depending on some input.
#Comparison operators.
- to compare two vlaues, left and right, they return or they give us a true or false value.
- they become very useful in the real world when we are working with data that is unknown.
> // greater than
< // less than
>= // greater than or equal to
<= // less than or equal to
== //equality
!= //not equal
=== //strict equality
!== //strict non-equality
- Let's say we are making a new web site. You have to be over 18 when you sign up. we still didn't make any decisions and just put comparison operator and just testing. And we got true or false value.
let age = 31 ; // let's say it is hided
age >= 18; // true
- Notice these all return a Boolean.
- You can also compare strings, it is uncommon though. Just be careful, things aget dicey when dealing with case, special characters. and accents. \
- Every character, they all have an underlying code, a numeric code, something called unicode.
'A' > 'a' // true
'@' < 'A' // ture
# Comparisons
- We have double equal sign and triple equal sign. It is important to know the difference.
- == (double equals) : checks for equality of value, but not equality of type. It coerces both values to the same type and then compares them. This can lead to some unexpected results.
1 == 1 // true
1 == "1" // true : BUT technically, these are not the same one cuz one of them is number and the other one is a string.
- Double equal convers them to the same type and then compares. It doesn't care about the type.
0 ==' ' ; // true
0 == false; // true
null==undefined// true
- ===( Triple equals) : Checks for equality of value and type. It is not goingto convert to the same type.
1 === '1' // false
0 === false // false
- You should just try to use triple equality all the time to know the type as well.
# Console / Alert / Prompt
- console.log() : Prints arguements to the console. You can also add multiple arguments
console.log(1+4 , "HI", true) // 5 "HI" true
- console is also object. You usually use log / error etc.
- alert() : print something to user not on the console.
- prompt() : accpet an argument. It pops up and asks the user to enter something. Normally what we do is save that to a variable like [let userInput = prompt{'please enter a number'}]. we can get some user input in this way.
- With prompt, you can only get 'string' value. If you want to get number value, you can use [parseInt() ]
parseInt(userInput)
parseInt(userInput) + 1
# Running code from a File
- On VS code, the only thing you need to make javascript file is put .js to file.
- Also you need to connect to your HTML file with JS file.
<script src = "app.js"></script>
- Unlike HTML or CSS , you cannot see the result of code on console right away. You need to use console.log() to see it. But if you made a variable, you still cannot see it but are able to access to the variable over the script.
- We usually put the <script> tag at the bottom of <body>tag.
# If (Conditional statements)
- When you have two different outcomes, you can handle it with conditional statements making decisions with your code.
- You have parentheses after if which is condition. This condition simply evaluate if anything is true or flase. If it is evaluated true, code in curly braces will exacute. If that condition is false, nothing happens.
let rating = 3;
if(rating === 3) {
console.log("YOU ARE A SUPERSTAR!")
}
# Else - If 구문
- If if part is false, else part is working.
const dayOfWeek = 'Monday';
if(dayOfWeek ==='Monday'){
console.log('I have Monday!')
}else if(dayOfWeek==='Saturday'){
console.log('I love Saturday')
}
- You can make 'else if' as many as you want.
- Let's make another example about age. When it comes to conditions, it works in order. If the first condition is false then the second one will be working. The second code is running only when the first one is false. If we make it to this point. we're already guaranteed not to be less than five.
let age = 8;
if(age<5){
console.log('You are a kid. You get in for free! ')
}else if(age< 10){
console.log('You are a child. You pay $10 ')
}else if(age<65){
console.log('You are an adult')
}
- The order matters \
- In this example, the conditon should be more tigher. It is still working when the age is negative number or freaking large age. Also you don't even check it if it is number or not.
# Else
- else is going to be the last part. We don't have to specify any conditon. If there is nothing to be matched, else part runs.
- You don't need to add any possible optional conditons, but just write else and it will print out
const dayOfWeek = prompt('enter a day').toLowerCase();
if(dayOfWeek ==='Monday'){
console.log('I have Monday!')
}else if(dayOfWeek==='saturday'){
console.log('I love Saturday')
}else if(dayOfWeek==='firday'){
console.log('Friday is decent, especially after work!')
}else if(dayOfWeek==='tuesday'){
console.log('meh')
}else if(dayOfWeek==='wendesday'){
console.log('meh')
}else if(dayOfWeek==='thurday'){
console.log('meh')
}else{
console.log('I love sunday')
}
- One thing you should know is you can get 'I love sunday' even though it is not valid day of week. You need to check If it is valid day of week or not.
- Another way to improve this code is that you can down casing everything or upper casing everything. We can eliminate any user capitalization -> prompt('enter a day').toLowercase();
#Truthy and Flasy values.
- All JS values have an inherent truthyness or falsyness about them.
- Falsy values : flase / 0 / ""(empty string) / null/ undefined / NaN // Everyting else is truthy!
const userInput = prompt('Enter something');
if(userInput){
console.log('truthy')
}else{
console.log('falsy')
}
- When you get some value throught prompt, it is considered truthy unless the values are falsy values.
# AND(Logical Operator)
- AND : Both sides must be true, for the entire thing to be true.
1 <= 4 && 'a'==='a' ; // true
9>10 && 9>=9 ; //false
'abc'.legnth === 3 && 1+1 ===4 ; //false
- In order to be entire thing consideing to be true, and left and right thing must be true. Both of them must be true to be true.
const password = prompt('Enter your password')
if(password.length>= 6 && password.indexOf(' ')===-1) //password 길이가 6이상이고 indexOf(' ' )===-1(공백값이 없다) 를 동시에 조건식으로 넣을 수 있음.{
console.log('Valid Password')
}else{
console.log('Incorrect format')
}
#OR(Logical Operator)
- The symbol we use for OR is two pipe characters. ||
- OR : If one side is true, the entire thing is true.
//only one side needs to be true!
1 !== 1 || 10 === 10 // true
10/2 === 5 || null // true
0 || undefined //false
//0-5 free
//5-10 $ 10
//10-65 $20
// +65 free
const age =
if(age > 0 && age <5 || age > 65){ //age > 0을 넣지 않으면 -10해도 free 값을 가지게 됨
console.log('FREE');
}else if(age >= 5 && age < 10 ){
console.log('$10')
}else if(age > =10 && age < 65){
console.log('$20')
}else{
console.log('Invalid age')
}
- When 'And' and 'Or' is combined, AND is always first proirity. If you prefer , though, you can add parentheses just to make it clearer to you.
#NOT (Logical Operator)
- NOT : ! experssion returns true if expresson is false.
- This one actually doesn't really combine two expressions, but it operates upon an expression. It is going to negate the value.
- Single exclamation mark means NOT.
!null // true
! (0===0) // false
!(3<=4) // false
let firstName = prompt('Enter your first name');
if(!firstName){ // firstName ===''으로 공백이 될때를 표시할수도 있지만 NOT 표시인!로 표시도 가능
firstName = prompt('Try again!')
}
- You can flip any complicated code with an exclamation mark. \
# Switch
- The switch statement is another control-flow statement that can replace multiple if statements.
- This syntax is not really used that much so No need to memorize it.
const day = 2;
switch(day) {
case 1:
console.log('Monday!')
case 2:
console.log('Tuesday!')
case 3:
console.log('Wendesday!')
case 4:
consol.log('Thursday'!)
}
// you will get Tuesday Wendesday Thursday all together
- The default behavior of Switch is that whenever there's a match, the switch starts executing the code from insdie this case and then it keeps going and going until it hits a break.
- break : we generally want to put a break at the end of one of these cases in order to make it stop.
const day = 2;
switch(day) {
case 1:
console.log('Monday!')
break;
case 2:
console.log('Tuesday!')
break;
case 3:
console.log('Wendesday!')
break;
case 4:
consol.log('Thursday'!)
break;
default:
console.log('I Don't know that')
}
// you will get tuesday!
- default : think of that as an outsider, if nothing else matched default.
'Udemy - The web developer camp' 카테고리의 다른 글
JavaScript Object Literals (0) | 2022.09.09 |
---|---|
JavaScript Arrays (0) | 2022.08.23 |
Javascript string (0) | 2022.08.04 |
JavaScript (0) | 2022.07.30 |
가격표만들기 (0) | 2022.07.26 |
댓글