This is my third week in JavaScript history.Since I've been dealing with Python for a long time, there were only two scopes of variables: global or not, but recently I realized that JavaScript has other scopes such as let
and const
.
I understand the difference between the two, but when I try to rewrite the source code I wrote only with let
and const
, I find that var
is good.
function hoge(hoge1,hoge2){
if(hoge1==="abc"){
var hoge3 = "def";
} else if(hoge1==="def"){
var hoge3 = "ghi";
}
return hoge1+hoge2+hoge3;
}
In the above source code, it's like, "I want to change the value of hoge3
depending on the value of hoge1
, but I want to handle hoge3
outside the block!" (although return
for each if
)
As far as the information on the Internet is concerned, there are many opinions that "var is not necessary" for safety reasons. Can I still use var
if I want to declare a common variable in a function like this...?
Or if there's a better way, I'd appreciate it if you could let me know! Thank you.
javascript
The let
scope is valid among subblocks, so
Declare outside the if
subblock.
function hoge(hoge1,hoge2){
let hoge3 = "aaa";
if(hoge1==="abc"){
// hoge3 declared in line 2
hoge3 = "def";
} else if(hoge1==="def"){
// hoge3 declared in line 2
hoge3 = "ghi";
} else{
// Declaring a variable of the same name in a subblock is a different variable
// Does not affect hoge3 in line 2
let hoge3 = "jkl";
}
return hoge1+hoge2+hoge3;
}
hoge("abc", "xyz"; // = "abcxyzdef"
hoge("def", "xyz"; // = "defxyzghi"
hoge("ghi", "xyz"; // = "ghixyzaaa"
"If the purpose of the if...else part is to ""calculate one value according to the conditions,"" I think it is better to make it into a function."
function hoge(hoge1,hoge2){
consthoge3=(function calcHoge3(hoge1){
if(hoge1==="abc"){
return "def";
} else if(hoge1==="def"){
return "ghi";
}
}) (hoge1);
return hoge1+hoge2+hoge3;
}
Good points
Small scope
Calculating the value is the only purpose
I don't use var that tends to behave strangely, so I'm relieved to know that strange behavior doesn't occur
What's wrong
Good point
Small scope
Calculating the value is the only purpose
I don't use var that tends to behave strangely, so I'm relieved to know that strange behavior doesn't occur
Small scope
You can make it clear that the only purpose is to calculate the value
I don't use var, which tends to behave strangely, so I'm relieved to know that it doesn't happen
Bad points
If you have an if expression like Ruby and Scala, it's easy to write.
How about this one?
export const hoge=(hoge1,hoge2)=>{
let hoge3 = ' '
if(hoge1==='aiueo')hoge3='kakikukeko'
else if(hoge1==='oeuia')hoge3='aiueo'
return hoge1+hoge2+hoge3
}
// or
export default {
hoge(hoge1,hoge2){
// same process...
}
}
© 2024 OneMinuteCode. All rights reserved.