DEV Community

Discussion on: Golang for JavaScript developers - Part 1

Collapse
 
marcellothearcane profile image
marcellothearcane
if val := getVal(); val < 10 {
    return val
} else {
    return val + 1
}

This is not possible in JS

What does it do?

Collapse
 
deepu105 profile image
Deepu K Sasidharan

Sorry, I should have explained it better. I'll update the post

Collapse
 
vinceramces profile image
Vince Ramces Oliveros

the variable is scoped to the if statement. Thus, it is much more readable. might be that the getVal() function would be like this.

func getVal() int{
    // return any number
    return 0
}

compare to javascript

// given by the example. the `val` is mutable
let val = getVal()
if(val < 10){
   return val
}
else{
  return val + 1
}
Collapse
 
nmhillusion profile image
nmhillusion

in golang,
after if block, variable val continues existing? Or it just exists in the if block?

Thread Thread
 
vinceramces profile image
Vince Ramces Oliveros

val is no longer accessible after the if statement. the variable is scoped to the if block

Collapse
 
deepu105 profile image
Deepu K Sasidharan

Thanks